【问题标题】:MobX decorators not workingMobX 装饰器不起作用
【发布时间】:2017-06-04 17:21:03
【问题描述】:

我无法让 @observable 和 @computed 等装饰器在我的项目中工作。

这是我的文件。

package.json:

{
  "name": "heroku-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-plugin-syntax-decorators": "^6.13.0",
    "mobx": "^3.1.11",
    "mobx-react": "^4.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-1": "^6.24.1",
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

App.js:

import React, { Component } from 'react';
import './App.css';
import GameBoard from './components/game-board';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
        </div>
        <GameBoard />
      </div>
    );
  }
}

export default App;

.babelrc:

{
  "presets": [
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}

当我在我的类声明之前添加 @observer 装饰器(@observer class App extends Component {...})时,我收到此错误:

Failed to compile
./src/App.js
Syntax error: Unexpected token (7:0)

   5 | import { inject, observer } from 'mobx-react';
   6 | 
>  7 | @observer class App extends Component {
     | ^
   8 |   render() {
   9 |     return (
  10 |       <div className="App">

【问题讨论】:

    标签: javascript reactjs react-native mobx mobx-react


    【解决方案1】:

    看起来您使用的是create-react-app,但没有使用eject。为了使用装饰器,您应该制作它。或者使用custom-react-scripts 作为替代。

    【讨论】:

      【解决方案2】:

      使用create-react-app时安装mobx的正确方法如下;

      1. create-react-app ExampleApp
      2. npm run eject
      3. npm install --saveDev babel-plugin-transform-decorators-legacy
      4. 立即更新您的 .babelrc 文件(使用 transform-decorators-legacy)
      5. npm install --save mobx mobx-react

      这应该可以解决问题。

      【讨论】:

        【解决方案3】:

        就我而言,我不使用“stage-1”,但我有以下插件

        "plugins": [
            "transform-decorators-legacy",
            "transform-class-properties"
          ]
        

        以及 package.json 中的这些依赖项

        "babel": "^6.23.0",
        "babel-loader": "^7.1.2",
        

        当您尝试不同的配置时,请确保清除 public/packs 文件夹。我在缓存文件方面遇到了一些问题。

        【讨论】:

          猜你喜欢
          • 2017-03-21
          • 1970-01-01
          • 2020-07-06
          • 2017-09-28
          • 1970-01-01
          • 2019-03-09
          • 2016-03-14
          • 2020-11-09
          相关资源
          最近更新 更多