Mobx: autorun is not firing

Created on 22 Aug 2016  ยท  4Comments  ยท  Source: mobxjs/mobx

So, not sure I have a wrong understanding of autorun

import {observable, reaction, autorun } from 'mobx';

const store = observable({
   box: {
     x: 100,
     y: 0
   }}
);
autorun(()=>
  console.log("reaction 1:", store.box)
)

export default store;

I am expecting autorun to be fired everytime store changes.

import React, { PropTypes, Component } from 'react';
import { action } from 'mobx';
import {observer} from 'mobx-react';

@observer
export default class BoxComponent extends Component {

  render() {
    const { box } = this.props;

    const divStyle = {
      top: box.y,
      left: box.x,
      position: 'absolute'
    };

    return (
        <div
          draggable="true"
          style={divStyle}
          onDrag={this.handleDrag}
        >
        Box1
        </div>
    );
  }

  @action
  handleDrag = (e) => {
    const { box } = this.props;
    if (e.nativeEvent.clientX != 0 && e.nativeEvent.clientX != 0) {
            box.x += e.nativeEvent.offsetX;
            box.y += e.nativeEvent.offsetY;
    }

  }
}

But when drag even happened, it is not firing the console.log. HMR again!!??

Source code available:
https://github.com/tweakmy/redux-convert-to-mobx.git
in branch: mobx

โ” question

Most helpful comment

@tweakmy, nope, you are using store.box in autrorun, and it was never changed

var prev = store.box;
store.box.x = 10;
prev === store.box // true

so autorun is not firing.

You can use observe(store.box, change => console.log(change)) if you're interested in all changes inside box object.

All 4 comments

@tweakmy, nope, you are using store.box in autrorun, and it was never changed

var prev = store.box;
store.box.x = 10;
prev === store.box // true

so autorun is not firing.

You can use observe(store.box, change => console.log(change)) if you're interested in all changes inside box object.

Thanks, that will do. I think I know what is the problem, is my understanding with const. Thanks for pointing out the obvious.

Make sure to read: http://mobxjs.github.io/mobx/best/react.html. It should make it pretty clear what MobX will react to and what not (and why that makes sense)

Closing issue as question seems answered. Feel free to reopen if needed

Was this page helpful?
0 / 5 - 0 ratings