How to use mobx

Comprehensive mobx code examples:

How to use mobx.trace:

5
6
7
8
9
10
11
12
13
14
var mobx_1 = require("mobx");
var Message_1 = __importDefault(require("./types/Message"));
var message = new Message_1.default("Foo", { name: "Michel" }, ["Joe", "Sara"]);
var disposer = mobx_1.autorun(function () {
    console.log(message.title);
    mobx_1.trace();
});
message.updateTitle("Bar");
console.log(mobx_1.getDependencyTree(disposer));
message = new Message_1.default("Bar", { name: "Michel" }, ["Joe", "Sara"]);

How to use mobx.isObservable:

169
170
171
172
173
174
175
176
177
178
}
else if (null == prev ||
    null == next ||
    !object.isObject(prev) ||
    !object.isObject(next) ||
    mobx.isObservable(prev) ||
    mobx.isObservable(next)) {
    return strictMode ? prev !== next : prev != next;
}
if (ignoreUndefined) {

How to use mobx.isBoxedObservable:

How to use mobx.configure:

321
322
323
324
325
326
327
328
329
330
331
332
    };
}


var optimizeScheduler = function (reactionScheduler) {
    if (typeof reactionScheduler === "function") {
        mobx.configure({ reactionScheduler: reactionScheduler });
    }
};


exports.Observer = ObserverComponent;

How to use mobx.Reaction:

164
165
166
167
168
169
170
171
172
173
}
var wantedForceUpdateHook = options.useForceUpdate || useForceUpdate;
var forceUpdate = wantedForceUpdateHook();
var reaction = React.useRef(null);
if (!reaction.current) {
    reaction.current = new mobx.Reaction("observer(" + baseComponentName + ")", function () {
        forceUpdate();
    });
}
var dispose = function () {

How to use mobx.set:

16
17
18
19
20
21
22
23
24
    if (isBoxed) {
      observable.set(value)
    } else if (isPropObservable) {
      target[key] = value
    } else {
      mobx.set(observable, value)
    }
  } catch (error) { }
}

How to use mobx.transaction:

315
316
317
318
319
320
321
322
323
324
325
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return mobx.transaction(function () { return fn.apply(context, args); });
    };
}


var optimizeScheduler = function (reactionScheduler) {

How to use mobx.getDependencyTree:

131
132
133
134
135
136
137
138
139
140
141
142


function printDebugValue(v) {
    if (!v.current) {
        return "<unknown>";
    }
    return mobx.getDependencyTree(v.current);
}


var EMPTY_ARRAY = [];
function useUnmount(fn) {

How to use mobx.isObservableProp:

998
999
1000
1001
1002
1003
1004
1005
1006
1007
this.__repository = options.repository;
this.abortController = new AbortController();

// Find all attributes. Not all observables are an attribute.
lodash.forIn(this, function (value, key) {
    if (!key.startsWith('__') && mobx.isObservableProp(_this2, key)) {
        invariant(!FORBIDDEN_ATTRS.includes(key), 'Forbidden attribute key used: `' + key + '`');
        _this2.__attributes.push(key);
        var newValue = value;
        // An array or object observable can be mutated, so we want to ensure we always have

How to use mobx.makeObservable:

2
3
4
5
6
7
8
9
10
11
12
13
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }


var _require = require('mobx'),
    autorun = _require.autorun,
    observable = _require.observable,
    makeObservable = _require.makeObservable;


console.log(observable, 'observable'); // class A{
//     @observable state = {
//         key:10

How to use mobx.toJS:

1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
    key: '__toJSAttr',
    value: function __toJSAttr(attr, value) {
        var casts = this.casts();
        var cast = casts[attr];
        if (cast !== undefined) {
            return mobx.toJS(cast.toJS(attr, value));
        }
        return mobx.toJS(value);
    }
}, {

How to use mobx.spy:

39
40
41
42
43
44
45
46
47
48
49
  return observable
}


function namedCrossTabDecorator (name) {
  return function (target, key, descriptor) {
    mobx.spy(function (event) {
      if (event.type !== 'add') return
      if (event.key !== key) return
      if (!target.isPrototypeOf(event.object)) return

How to use mobx.createTransformer:

143
144
145
146
147
148
149
150
151
152
var transformFolder = m.createTransformer(function (folder) {
        return new DisplayFolder(folder, state);
});

// 返回每个文件夹的字符串列表
var stringTransformer = m.createTransformer(function (displayFolder) {
        var path = displayFolder.path;
        return path + "\n" +
                displayFolder.children.filter(function(child) {
                        return child.isVisible;

How to use mobx.autorun:

602
603
604
605
606
607
608
609
610
    relations: this.__activeRelations,
    comparator: comparator
});

// Oh gawd MobX is so awesome.
var events = mobx.autorun(function () {
    var models = _this7.filter(filter);
    store.models.replace(models);
    store.sort();

How to use mobx.when:

9
10
11
12
13
14
15
16
17
18

const obs = utils.fromPromise(p)
expect(obs.value).toBe(undefined)
expect(obs.state).toBe("pending")

mobx.when(
    () => {
        return obs.state === "fulfilled"
    },
    () => {

How to use mobx.computed:

9
10
11
12
13
14
15
16
17
18
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }
function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }
var _require = require('mobx'),
  observable = _require.observable,
  computed = _require.computed;
var Store = (_class = /*#__PURE__*/function () {
  function Store() {
    _classCallCheck(this, Store);
    _defineProperty(this, "MASKED_CC_PREFIX", '************');

How to use mobx.extendObservable:

27
28
29
30
31
32
33
34
35
36
constructor() {
  this.contentsDir = join(__dirname, '..', '..', 'static', 'contents')
  this.items = {}

  /** Extend the store with observable and computed properties. */
  extendObservable(this, {
    contents: {},
    updatedItems: [],
    updateInProgress: false,
    updateAgain: false,

How to use mobx.makeAutoObservable:

124
125
126
127
128
129
130
131
132
133
eventSequenceDictName = "midiEventSequence";
eventSequence;

constructor(rootStore) {
  // i.e. quantizedEventSequence = [{"36": [2, 100], "42": [0, 127]}, ...]
  makeAutoObservable(this);
  this.root = rootStore;
  this.eventSequence = new EventSequence();

  this.reactToParamsChange = reaction(

How to use mobx.action:

61
62
63
64
65
66
67
68
69
      //enqueueEvents([{ section: 'test', type: 'test.blah' }])
    })
  }
}

const processReceivedError = action(error => {
  console.error('processReceivedError', error)
  state.errorCount += 1
})

How to use mobx.reaction:

7
8
9
10
11
12
13
14
15
16

module.exports = class State extends PersistentState {
  constructor() {
    super(fields.all, fields.persistent);
    // todo: mobx.toJS -> mobx.asStructure
    mobx.reaction(() => mobx.toJS(this.files), mobx.action(this._verifySelectedFile.bind(this)));
  }

  /**
   * On every change of files check that selectedFile is found there and reset if not found

How to use mobx.observable:

How to use mobx.runInAction:

53
54
55
56
57
58
59
60
61
62
  .then(action(() => {
    state.successCount += 1
  }))
}
else {
  runInAction(() => {
    state.successCount += 1

    //enqueueEvents([{ section: 'test', type: 'test.blah' }])
  })