Mobx-state-tree: Why computed getter get called even observable properties didn't change?

Created on 2 Apr 2018  路  4Comments  路  Source: mobxjs/mobx-state-tree

The following is my code

import React from "react"
import { types } from "mobx-state-tree"
import { observer } from "mobx-react"

const AppModel = types.model({
    name: types.string
}).views(self => ({
    get displayName() {
        return self.name + '_' + Date.now();
    }
}));

const store = AppModel.create({ name: 'Raymond' })

console.log(store.displayName);
console.log(store.displayName);
console.log(store.displayName);

You can copy it to https://mattiamanzati.github.io/mobx-state-tree-playground/ to reproduce it.
What I expected the 3 console.log should show the same, but its not.

This even not work if I switch to pure mobx..

class POCStore {
    @observable
    name: string;
    @computed get displayName() {
      return `${this.name}'_${Date.now()}`;
    }
    constructor(name: string) {
      this.name = name;
    }
  }
const s = new POCStore('Raymond');
console.log(s.displayName);
console.log(s.displayName);
console.log(s.displayName);
question

All 4 comments

@raymondsze your displayName view is executed each time you request its value, obviously Date.now() will be different for every invocation. I'd say the result is quite logical?

If you are looking to retain that unique suffix, define it as a property of the model, not - view.

@jayarjo
I am doing POC on the mobx-state-tree becoz I am tired of redux now...
Seems I misunderstand something after several testing...

What I thought was..
The getter of "computed" value or "views" value would only be called again if the observable properties changed. If the observable properties didn't change, it should return the previous memorized value.

Therefore, even I use Date.now(), the three console.log output should be logically the same.

After several testing, seems the "computed" or "views" behave correctly if reacting to Component marked with "@observer". So what I think right now is the "computed" or "views" have meaning to some thing marked "@observer" or equivalent instead of model itself. If that's true, it's just my misunderstanding, then the issue could be closed.

Thanks a lot.

@raymondsze as you've already found out - the memoization only works if you observe the view (a view is a mobx computed, see computed ). the memoization it is automatically suspended if it is not observed anymore since memory can be freed like that.

Thanks for quick reply! :+1: Lets close it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ShootingStarr picture ShootingStarr  路  4Comments

elado picture elado  路  4Comments

marszhou picture marszhou  路  3Comments

FredyC picture FredyC  路  3Comments

misantronic picture misantronic  路  3Comments