"this" 在我的 Class 中未定义

"this" is undefined inside my Class

我的小型待办事项应用程序有问题。每次我尝试删除项目时都会出现错误 Cannot read property 'todos' of undefined

为什么 this 绑定在 addTodo 而不是 removeTodo 内?

这里触发完成:<button onClick={() => removeTodo(id)}> X </button>

演示 JSfiddle

谢谢。

您可以将 removeTodo 变成 属性 初始化箭头函数或使用 action.bound 装饰器。你还必须使用 MobX 数组 replace 这样你就不会丢失引用:

removeTodo = (id) => {
  var filtered = this.todos.filter(todo => todo.id !== id);
  this.todos.replace(filtered);
}

或者:

@action.bound
removeTodo(id) {
  var filtered = this.todos.filter(todo => todo.id !== id);
  this.todos.replace(filtered);
}