1

通过以下代码,我收到此错误:

error: Error: [mobx-state-tree] Cannot modify 
'AuthenticationStore@<root>', the object is protected and can only be 
modified by using an action.

有问题的代码(生成器):

.model('AuthenticationStore', {
    user: types.frozen(),
    loading: types.optional(types.boolean, false),
    error: types.frozen()
  })
  .actions(self => ({
    submitLogin: flow(function * (email, password) {
      self.error = undefined
      self.loading = true
      self.user = yield fetch('/api/sign_in', {
        method: 'post',
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          'user' : {
            'email': email,
            'password': password
          }
        })
      }).then(res => {
        return res.json()
      }).then(response => {
        self.loading = false // the error happens here!
        return response.data
      }).catch(error => {
        console.error('error:', error)
        // self.error = error
      })
    }), ...

问题:这在生成器中是不允许的吗,是否有更好的方法来更新这个特定状态,或者它是否需要被 try/catch 包装?

一如既往地感谢任何和所有反馈!

4

1 回答 1

5

问题是您正在调用then由返回的 Promise fetch(),而您传递给的函数then不是一个动作。请注意,动作(或流)中运行的函数不计入动作本身。

由于您使用的是yield,因此您不需要调用thenorcatch返回的 Promise fetch()。相反,将其包装在 try/catch 中:

submitLogin: flow(function* (email, password) {
  self.error = undefined;
  self.loading = true;
  try {
    const res = yield fetch('/api/sign_in', {
        method: 'post',
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          'user' : {
            'email': email,
            'password': password
          }
        })
    });
    const response = yield res.json();
    self.loading = false;
    self.user = response;
  } catch(error) {
    console.log('error: ', error);
    self.error = error;
  }
}
于 2018-11-15T22:22:18.970 回答