MobX 'this' 在 setter 操作中未定义

jan*_*iks 3 javascript reactjs mobx mobx-react create-react-app

我正在使用最近的 create-react-app 设置和 JS 和mobx decorate方法。

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
Run Code Online (Sandbox Code Playgroud)

我可以使用商店并读取空的userscurrentUser可观察的,但是当我尝试使用该setUsers操作时,我收到以下错误:

TypeError: Cannot set property 'users' of undefined

它看起来像this未定义,但这是大多数 MobX 教程显示的常见方式,不应抛出错误......

jan*_*iks 6

当使用MobX香草JavaScript中,不同的情况下可能会有点混乱... MobX推出绑定action小号使它更容易些。

正确的装饰使用action.bound是:

setUsers: action.bound
Run Code Online (Sandbox Code Playgroud)

或者我们可以使用 lambda 函数来确保上下文正确:

setUsers = value => {
  this.users = value
}
Run Code Online (Sandbox Code Playgroud)

任何一种更改都将确保 setter 函数的上下文正确并且可以使用该类this。查看类似问题答案以获得更详细的解释。

  • 2021 年在这里!答案中的链接已损坏。这里[新的](https://mobx.js.org/actions.html#actionbound) (2认同)