Yes, respond to event callbacks with this equal to zero. Since you only onClick method, not store as the context.
Decision
You must set this context yourself. You can do this in the following ways.
Bad practice:
as @Eduard said you can warp it into an arrow function. the Arrow function ensures that the this context remains unchanged in the body of the function:
<button onClick={() =>store.change_me()}>{store.me}</button>
You can also use the bind method:
<button onClick={store.change_me.bind(store)}>{store.me}</button>
it is basically the same.
Why do they work poorly? on each call to render() these methods are recreated. and can lead to unnecessary unnecessary re-rendering.
Innovate experience
mobx provides an action.bound that wraps the function in the appropriate context:
@mobx.action.bound change_me(){ this.me = 'test 1'; }
Alternatively, defining an es6 class allows you to correctly define this context yourself:
@mobx.action change_me = () => { this.me = 'test 1'; }
See arrow function. behind the scenes: instead of defining a function / method in the prototype of the store class. the method is created in the constructor , so the context variable this always corresponds to an instance of the class.
so that:
var a = new Store(); // a.me = 'test' var b = new Store(); // b.me = 'test' a.change_me = b.change_me; // change_me function contains its own this context. a.change_me(); // a.me = 'test' b.me = 'test 1'
source share