Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 864
janniks Avatar asked Dec 08 '19 22:12

janniks


1 Answers

When using MobX with vanilla JavaScript, different contexts can be a bit confusing... MobX introduced bound actions 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.

like image 191
janniks Avatar answered Oct 03 '22 09:10

janniks