mobx 启用严格模式后,action中修改值报错,被阻止
一个简单的store,登录、登出和获取当前session中的用户
class UserStore {
@observable
detail = {};
@observable
userInfoId;
@observable
nickName;
@action
doLogin = (data) => {
const _this = this;
return axios.post('/login', data).then(resp => {
if(resp.success && resp.data) {
message.success(`欢迎回来,${resp.data.nickName}`);
_this.detail = resp.data;
_this.userInfoId = resp.data.userInfoId;
_this.nickName = resp.data.nickName;
}
return resp;
});
}
@action
doLogout = () => {
const _this = this;
return axios.post('/logout').then(resp => {
if(resp.success) {
message.success('登出成功');
_this.detail = {};
_this.userInfoId = '';
_this.nickName = '';
}
return resp;
});
}
@action
doFetch = () => {
const _this = this;
return axios.get('/user-info/current').then(resp => {
if(resp.success && resp.data) {
_this.detail = resp.data;
_this.userInfoId = resp.data.userInfoId;
_this.nickName = resp.data.nickName;
}
return resp;
});
}
}
在配置 configure({enforceActions: 'observed'})
后
登录、登出都会报错,被阻止更新了
mobx.module.js?daf9:98 Uncaught (in promise) Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: UserStore@3.userInfoId
at invariant$$1 (mobx.module.js?daf9:98)
at fail$$1 (mobx.module.js?daf9:93)
at checkIfStateModificationsAreAllowed$$1 (mobx.module.js?daf9:1075)
at ObservableValue$$1.prepareNewValue (mobx.module.js?daf9:686)
at ObservableObjectAdministration$$1.write (mobx.module.js?daf9:3509)
at UserStore.set [as userInfoId] (mobx.module.js?daf9:3732)
at eval (UserStore.jsx?3e72:105)
后来尝试把每个字段拿出来:
@action
updateUserInfoId(userInfoId) {
this.userInfoId = userInfoId;
}
@action
updateDetail(detail) {
this.detail = detail;
}
@action
updateNickName(nickName) {
this.nickName = nickName;
}
@action
doLogin = (data) => {
const _this = this;
return axios.post('/login', data).then(resp => {
if(resp.success && resp.data) {
message.success(`欢迎回来,${resp.data.nickName}`);
//_this.detail = resp.data;
//_this.userInfoId = resp.data.userInfoId;
//_this.nickName = resp.data.nickName;
_this.updateUserInfoId(resp.data.userInfoId);
_this.updateDetail(resp.data);
_this.updateNickName(resp.data.nickName);
}
return resp;
});
}
这次可以成功更新了。
不是很明白之前直接在doLogin里面更新有什么问题?
比较奇怪的是,doFetch这个方法,却能直接更新成功。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试在runInAction中操作,具体看文档
runInAction