Mobx changing observable values outside of action
A function that alters the observables needs to be wrapped in action
, so use it on the callback as well:
getAllTodos: action(() => {
Services.getAllTodos()
.then(action((response) => {
state.items.replace(response.data);
})).catch((error) => {
console.error(error);
});
})
As stated in the MobX docs here:
The action wrapper / decorator only affects the currently running function, not functions that are scheduled (but not invoked) by the current function! This means that if you have a setTimeout, promise.then or async construction, and in that callback some more state is changed, those callbacks should be wrapped in action as well!
Thus, you'd have to wrap the scheduled promise.then
here in an action as well, apart from the parent function. (Note that you'd only be able to use the @action
on the class-level function)
There are two ways of doing it:
action(
asyncFunction().then(
action((args) => {
// Your function body here
})
)
)
--or--
Use the @action.bound
:
@action
asyncFunction().then(
yourStateModifyingFunction();
)
@action.bound
yourStateModifyingFunction() {
// Your function body here
}