繁体   English   中英

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 ,因此您无需调用thencatchfetch()返回的 Promise 。 相反,将其包装在 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;
  }
}
问题未解决?试试使用:帮您解决问题。
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM