score:1

With Mobx 6, decorators are becoming more discouraged and cumbersome to use (requiring makeObservable(this) to be called carefully in the constructor, even in subclasses.)

I therefore now find it cleaner to use

doStuff = action(() => {
    //  stuff logic
})

rather than

@action.bound
doStuff() { ...

or

@action
doStuff = () => { ...

This pattern with no decorators also works in older Mobx versions.

score:4

Since there is 2018, the best practice in React apps development is to use lambda functions as class properties instead of class methods.

The lambda function as class property resolves all issues that can happen with context. You don't have to bind methods to the specific context, if using it.

For example, you working with this in some class method:

export default class SomeClass {
    myProp = "kappa"

    myMethod() {
        console.log(this.myProp)
    }
}

In this case, if you will use it, e.g., like some event listener, this will be unexpectedly (actually, more than expected) change from SomeClass instance to other value. So, if you using class methods, you should modify you code like this:

export default class SomeClass {
    constructor() {
        this.myMethod = this.myMethod.bind(this)
    }

    myProp = "kappa"

    myMethod() {
        console.log(this.myProp)
    }
}

In constructor you are binding your class method to context of SomeClass instance.

The best way to avoid this kind of unnecessary code (imagine, that you have 10+ of this type of methods - and you should bind each of them), is to simply use lambda functions:

export default class SomeClass {
    myProp = "kappa"

    myMethod = () => {
        console.log(this.myProp)
    }
}

That's it! Lambda functions have no context, so this will always point to the SomeClass instance. So, now you can decorate you class property as you wish:

export default class SomeClass {
    myProp = "kappa"

    @action
    myMethod = () => {
        console.log(this.myProp)
    }
}

Note, that if you are using Babel, you have to use transform-class-properties plugin.

This question is more related to the core of JavaScript, so I advise you to read this MDN article for more information about this behavior.

Hope, this was helpful!

score:6

You can either use @action.bound decorator:

@action.bound
doSomething(){

    // logic

}

or use labmda function which will preserve the context:

@action
doSomething = ()=> {

    // logic

}

Related Query

More Query from same tag