Support for the experimental syntax 'decorators-legacy' isn't currently enabled
I tried adding the decorators-legacy
babel plugin and @babel/plugin-proposal-decorators
with { legacy: true }
in .babelrc
but no effect.
Anyone managed to get MobX decorators to work with CRA2?
Reactions in MobX are pretty similar to computed values, but the difference is that reactions trigger side effects and occur when our observables change. Reactions in MobX can either be UI changes or background changes—for example, a network request, a print on the console, etc.
Firstly, install dependencies:
yarn add react-app-rewired customize-cra @babel/plugin-proposal-decorators
Secondly, create config-overrides.js
in root directory with following contents:
const {
addDecoratorsLegacy,
override,
disableEsLint
} = require("customize-cra");
module.exports = {
webpack: override(
addDecoratorsLegacy(),
disableEsLint()
)
};
You should be able to use mobx + decorators now.
If you don't have mobx installed already, please run:
yarn add mobx mobx-react
.
Now you can use decorators.
I had same issue and ended up with using mobx4 where Decorators can be used without decorator syntax.
class Store {
//...
@action empty() {
this.data = []
}
@action add(e) {
this.data.push(e)
}
}
can be rewritten as
class Store {
//...
empty() {
this.data = []
}
add(e) {
this.data.push(e)
}
}
decorate(Store, {
add: action,
empty: action
})
You can use this feature out of the box from CRA2 and do not need to worry about transform decoracy plugin. Thanks Michel Weststrate for this stuff
https://medium.com/@mweststrate/mobx-4-better-simpler-faster-smaller-c1fbc08008da
Option 1: Using decorators with CRA v2
If you refer to Mobx documentation, you can get Mobx decorators to work with CRAv2 by using Typescript:
Decorators are only supported out of the box when using TypeScript in create-react-app@^2.1.1.
However, in some cases, you might still face issues when using Mobx with other react frameworks. In that case:
Option 2: Don't use decorators
A detailed step by step guide is documented here.
If you previously defined your observer react component as:
@observer
export default class MyComponent extends React.Component
Change it to:
const MyComponent = observer(class MyComponent extends React.Component{
/* ... */
});
export default MyComponent;
If you previously had:
@observable myElement = null;
You need to change it to:
myElement;
then:
decorate(MyComponent, {
myElement: observable,
})
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With