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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With