I\'m using MobX 2.2.2 to try to mutate state inside an async action. I have MobX\'s useStrict set to true.
@action someAsyncFunction(args) {
fetch(`http://loca
note that in async method you manualy have to start a new action/transaction after awaiting something:
@mobx.action async someAsyncFunction(args) {
this.loading = true;
var result = await fetch(`http://localhost:8080/some_url`, {
method: 'POST',
body: {
args
}
});
var json = await result.json();
@mobx.runInAction(()=> {
this.someStateProperty = json
this.loading = false;
});
}
I prefer to not use @mobx.action/runInAction directly but always place it on an private
method. And let public methods call private methods that actually update the state:
public someAsyncFunction(args) {
this.startLoading();
return fetch(`http://localhost:8080/some_url`, {
method: 'POST',
body: {
args
}
})
.then(res => res.json())
.then(this.onFetchResult);
}
@mobx.action
private startLoading = () => {
this.loading = true;
}
@mobx.action
private onFetchResult = (json) => {
this.someStateProperty = json;
this.loading = false;
}