通过下面的代码,我得到了这个错误:
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来包装它?
与往常一样,感谢提前的任何和所有的反馈!
发布于 2018-11-15 22:22:18
问题是,您正在根据then返回的承诺调用fetch(),而传递给then的函数不是一个操作。请注意,在操作(或流)中运行的函数不算作操作本身。
由于您使用的是yield,所以不需要根据fetch()返回的承诺调用then或catch。相反,将其包装为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;
}
}https://stackoverflow.com/questions/53306305
复制相似问题