Mobx invoke Action on Computed property

809 views Asked by At

this is the code:

@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));
}

so, the main goal is, When the profile data are not yet validated, we'll refetch it from server, then, while waiting the data changed, we'll give them the cached value from the localstorage.

Anddd.... my question is, Why do it give me a 'Computed value cannot invoke Action funtion' thing?

Thankyou! :D

1

There are 1 answers

0
mweststrate On BEST ANSWER

Computes are intended to be (conceptually) pure. And Actions are intended to be (conceptually) impure. So although technically it could be a fine combination, conceptually they aren't.

But fear not, just check the mobx-utilsorcomputed-async-mobx` packages. They might contain the the ready to use abstractions you are looking for.