score:10

Accepted answer

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

score:3

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
}


Related Query

More Query from same tag