Mobx doesn't observe classes in observable array

rob*_*rob 5 javascript reactjs mobx

If I push a class instance into an observable array in MobX then it is not observed. However if I push a literal object into an observable array then it will be observed.

The docs for observable arrays say that

"all (future) values of the array will also be observable"

so I am trying to understand why this happens.

For example the following code can be run in node:

let mobx = require('mobx');

class TodoStore {
  constructor() {
    this.todos = mobx.observable.array([]);

    this.todos.push({title:'todo 1'});
    this.todos.push(new Todo('todo 2'));
  }
}

class Todo {
  constructor(title) {
    this.title = title;
  }
}

let store = new TodoStore();

console.log('***initial state***');
mobx.autorun(() => {
  if(store.todos.length > 0) {
    console.log('first todo:', store.todos[0].title);
    console.log('second todo:', store.todos[1].title);
  }
});

console.log('***Updating todo 1***');
store.todos[0].title = 'todo 1 updated';

console.log('***Updating todo 2***');
//Why doesn't this trigger the autorun?
store.todos[1].title = 'todo 2 updated'; 
Run Code Online (Sandbox Code Playgroud)

this logs out

***initial state***
first todo: todo 1
second todo: todo 2
***Updating todo 1***
first todo: todo 1 updated
second todo: todo 2
***Updating todo 2***
Run Code Online (Sandbox Code Playgroud)

更新todo[1]不会触发自动运行。谁能解释为什么?我知道我可以手动使titleTodo 类上的属性可观察,但我想知道为什么我需要这样做。

mwe*_*ate 5

永远不会自动转换,以免干扰类可能对自身的任何内部假设。请参阅可观察对象的文档:-D

如果 value 是具有原型的对象、JavaScript 原语或函数,则将返回 Boxed Observable。MobX 不会使具有原型的对象自动可观察;因为这是它的构造函数的责任。在构造函数中使用 extendObservable,或者在其类定义中使用 @observable。

换句话说,请执行以下操作:

class Todo {
  constructor(title) {
    extendObservable(this, { title })
  }
}
Run Code Online (Sandbox Code Playgroud)