MobX 状态树生成器不允许修改成功承诺中的状态?

MobX State Tree generator does not allow modified state in a successful promise?

通过以下代码我得到这个错误:

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 包装?

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

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

由于您使用的是 yield,因此无需对 fetch() 返回的 Promise 调用 thencatch。相反,将其包装在 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;
  }
}