Moon soon
Moon soon

Reputation: 2856

Mobx: change states in action without runInAction still works

In mobx documentation:

action 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!

This above mean, I should wrap state changed with runInAction, like this following:

class App {
    @observable logined = false
    @action async login(payload){
        runInAction(() => {
            setTimeout(() => {
                this.logined = false 
            }, 1000)
        })
    }
}

Above works, but the weird is if i remove the runInAction block, code still works, this behaviour is inconsistent with the document said.

please check the fiddle.

Upvotes: 3

Views: 4204

Answers (2)

Nick Perkins
Nick Perkins

Reputation: 8294

An "action" allows you to make multiple state changes in one "batch" -- if you are only making one change, you don't need it.

Upvotes: 0

mweststrate
mweststrate

Reputation: 4978

This behavior is correct; unobserved data can be modified at will, as it cannot lead to further side effects, see: https://github.com/mobxjs/mobx/blob/master/CHANGELOG.md#310

Also not that it is always allowed to change state outside of actions as long as strict mode is not enabled (mobx.useStrict(true))

A PR to reflect this new behavior better in the docs would be appreciated! https://github.com/mobxjs/mobx/blob/gh-pages/docs/refguide/action.md

Upvotes: 1

Related Questions