admin管理员组

文章数量:1303353

Is there any way that a console.log will automatically fire whenever a mobx @observable changes value?

I would do it with mobx dev tools but it fires a huge amount of console logs so it's hard to pin point the property whose value I am tracking.

Is there any way that a console.log will automatically fire whenever a mobx @observable changes value?

I would do it with mobx dev tools but it fires a huge amount of console logs so it's hard to pin point the property whose value I am tracking.

Share asked Feb 2, 2017 at 13:18 alanbuchananalanbuchanan 4,1738 gold badges43 silver badges66 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You can do:

//store.js
import { autorun } from 'mobx';
autorun(() => {
  console.log(store.value); //value is an observable.
});

You can also use Reaction, For logging you'll probably want to use autorun, but you should know there's another option, which can gives you more control over when to run your callback.

I also like it because the syntax makes more sense:

import { reaction } from 'mobx'

class SomeStore {
    @observable item;
    @observable otherObservable;

    constructor() {
        reaction(
            // The callback will run only on change 
            // of observables described in this function
            () => this.item,
            // You can use whatever observables/puted values in this function
            // without making the function run on an unwanted observables change
            () => {
                if (this.otherObservable) {
                    doSometing();
                }
            }
        )
    }
}

There are more options to this function, you can read about it in the provided link.

本文标签: javascriptconsolelog a mobx observable whenever its value changesStack Overflow