Support for the experimental syntax 'decorators' isn't currently enabled (5:3):

This guide is targeted specifically to people who encountered this error while using MobX with ReactJS

Error

Now I know, its frustrating when you got this error, no worries, I know exactly what caused the error. Here was my code that caused the error:

// store.js
import { observable, action } from 'mobx';

class ProductStore {
  @observable products = [];

  @action
  addProduct(product) {
    this.products.push(product);
  }
}

const store = new ProductStore();
export default store;

Solutions tried

You might see this message in your console:

"Add @babel/plugin-proposal-decorators (https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators) to the 'plugins' section of your Babel config to enable transformation."

and you might have added this new dependencies in both .babelrc [source], babel.config.json [source], installing the dependencies in dev using npm [source], installing it as regular dependency [source], using react-app rewired to install the new dependency [source]. IT ALL DOESN'T WORK!!

That is because you are trying to use the decorators using the babel, and it doesn't coincide well with MobX.

Solution:

Then I came across this post, and I realized, MobX has it's own decorator class to use

Here is the modified version of code:

// store.js
import { makeObservable,observable,  computed, action, decorate  } from 'mobx';

class ProductStore {
  constructor() {
    makeObservable(ProductStore, {
      products: observable,
      addProduct: action
    })
  }
  products = [];

  addProduct(product) {
    this.products.push(product);
  }
}
const store = new ProductStore();
export default store;

What changed was, I used makeObservable (the latest version, since decorate doesn't exist in the latest version of MobX), instead of using the decorator "@observable" and vio la, the error is gone!


IMPORTANT:

Also, make sure your webpack.config.js is configured properly, if your babel looks like this

// webpack.config.js
module.exports = {

    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
  };
 

it's time to remove this

use: {
            loader: 'babel-loader',
          },

and you should be good to go!



Comments

Popular posts from this blog

How to add environment variables into Heroku container

Running CQL scripts in Cassandra