stu*_*ain 2 generator mobx mobx-react mobx-state-tree
通过下面的代码我得到这个错误:
error: Error: [mobx-state-tree] Cannot modify
'AuthenticationStore@<root>', the object is protected and can only be
modified by using an action.
Run Code Online (Sandbox Code Playgroud)
有问题的代码(生成器):
.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
})
}), ...
Run Code Online (Sandbox Code Playgroud)
问题:这在生成器中是不允许的吗?是否有更好的方法来更新这个特定状态,或者是否需要用 try/catch 来包装它?
一如既往,感谢所有反馈!
问题是您正在调用then返回的 Promise fetch(),并且您传递给的函数then不是操作。请注意,在操作(或流程)内运行的函数不算作操作本身。
由于您正在使用yield,因此不需要在 . 返回的 Promise 上调用then或。相反,将其包装在 try/catch 中:catchfetch()
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;
}
}
Run Code Online (Sandbox Code Playgroud)