通过出现以下错误的代码:
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进行包装?
一如既往地感谢以获取所有反馈!
答案 0 :(得分:1)
问题是您在then
返回的Promise上调用fetch()
,而传递给then
的函数不是动作。请注意,在某个动作(或流程)内运行的函数不算作该动作本身。
由于您使用的是yield
,因此不需要在then
返回的Promise上调用catch
或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;
}
}