Search code examples
javascriptmobx

MobX autorun doesn't get dependency it should


This code I took from https://mobx.js.org/understanding-reactivity.html

import { makeAutoObservable, autorun, getDependencyTree  } from "mobx";

class Message {
  title;
  author;
  likes;
  constructor(title, author, likes) {
    makeAutoObservable(this);
    this.title = title;
    this.author = author;
    this.likes = likes;
  }

  updateTitle(title) {
    this.title = title;
  }
}

let message = new Message("Foo", { name: "Michel" }, ["Joe", "Sara"]);

const disposer = autorun(() => {
  console.log(message.title);
});

console.log(getDependencyTree(disposer));
message.updateTitle("Bar");
message.updateTitle("gasdg");

But in consolse I get this:

Foo
index.js:114 {name: 'Autorun@2'}

It doesn't pick up message.title as dependency, please help me understand why!


Solution

  • By default make(Auto)Observable only supports properties that are already defined, so you need to define every property inside constructor or make it nullable like that: author = null, or add default value likes = 0:

    class Message {
      // Or add default values here
      title = '';
      author = null;
      likes = 0;
      constructor(title, author, likes) {
        // Initialise properties as first thing
        this.title = title;
        this.author = author;
        this.likes = likes;
    
        makeAutoObservable(this);
      }
    
      updateTitle(title) {
        this.title = title;
      }
    }
    

    Alternatively you might want to try to reconfigure how class properties initialisation works, using useDefineForClassFields TS compiler flag:

    "compilerOptions": {
      "useDefineForClassFields": true
    },