Mobx 在 Computed 属性 上调用 Action
Mobx invoke Action on Computed property
这是代码:
@computed
get user() {
if(!this.hasValidated)
this.reloadUserData();
return this.userData;
}
@action
reloadUserData() {
return new Promise(function(ok, err) {
if(!window.localStorage['atoken'])
err({id:24, detail:'User havn\'t logged in.'});
if(!window.localStorage['aprofile'])
apicall.get('user/detail').then((data)=>{
this.setProfile(data.data.content);
ok(true);
}).catch((derr)=>{
err({id:20, detail:derr});
});
else{
this.userData=JSON.parse(window.localStorage['aprofile']);
}
}.bind(this));
}
因此,主要目标是,当配置文件数据尚未验证时,我们将从服务器重新获取它,然后,在等待数据更改的同时,我们将从本地存储中为它们提供缓存值。
Anddd....我的问题是,为什么它给我 'Computed value cannot invoke Action funtion' 东西?
谢谢! :D
计算旨在(概念上)纯粹。并且 Actions 旨在(概念上)不纯。因此,尽管从技术上讲它 可以 是一个很好的组合,但从概念上讲它们不是。
但不要害怕,只需检查 mobx-utilsor
computed-async-mobx` 包。它们可能包含您正在寻找的随时可用的抽象。
这是代码:
@computed
get user() {
if(!this.hasValidated)
this.reloadUserData();
return this.userData;
}
@action
reloadUserData() {
return new Promise(function(ok, err) {
if(!window.localStorage['atoken'])
err({id:24, detail:'User havn\'t logged in.'});
if(!window.localStorage['aprofile'])
apicall.get('user/detail').then((data)=>{
this.setProfile(data.data.content);
ok(true);
}).catch((derr)=>{
err({id:20, detail:derr});
});
else{
this.userData=JSON.parse(window.localStorage['aprofile']);
}
}.bind(this));
}
因此,主要目标是,当配置文件数据尚未验证时,我们将从服务器重新获取它,然后,在等待数据更改的同时,我们将从本地存储中为它们提供缓存值。
Anddd....我的问题是,为什么它给我 'Computed value cannot invoke Action funtion' 东西?
谢谢! :D
计算旨在(概念上)纯粹。并且 Actions 旨在(概念上)不纯。因此,尽管从技术上讲它 可以 是一个很好的组合,但从概念上讲它们不是。
但不要害怕,只需检查 mobx-utilsor
computed-async-mobx` 包。它们可能包含您正在寻找的随时可用的抽象。