简体   繁体   中英

MobX 'this' is undefined in setter action

I am using a recent create-react-app setup with JS and the mobx decorate method.

import { observable, action, decorate } from 'mobx'

class UserStore {
  users = []
  currentUser = {}

  setUsers(value) {
    this.users = value
  }
}

decorate(UserStore, {
  users: observable,
  currentUser: observable,
  setUsers: action
})

export default UserStore

I can use the store and read the empty users and currentUser observables, but when I try using the setUsers action I receive the following error:

TypeError: Cannot set property 'users' of undefined

It looks like this in undefined, but this is the common way most MobX tutorials show and should not throw an error...

When using MobX with vanilla JavaScript, different contexts can be a bit confusing... MobX introduced bound action s to make this easier.

The correct decorate using action.bound would be:

setUsers: action.bound

OR we can use lambda functions to make sure the context is correct:

setUsers = value => {
  this.users = value
}

Either change will ensure the context of the setter function is correct and can use the class this . Check out the answers to a similar question for more detailed explanations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM