8

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

janniks
  • 2,942
  • 4
  • 23
  • 36

1 Answers1

10

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.

janniks
  • 2,942
  • 4
  • 23
  • 36
  • 2
    2021 here ! The link from the answer is broken. Here [the new one](https://mobx.js.org/actions.html#actionbound) – Emidomenge Apr 01 '21 at 13:38