首页 > 解决方案 > 添加计算装饰器会导致 TypeError

问题描述

我不能用@computed。如果我在下面运行我的代码,我会收到一个错误:

Uncaught TypeError: An element descriptor's .kind property must be either "method" or "field", but a decorator created an element descriptor with .kind "undefined"
    at _toElementDescriptor (app.js:46281)
    at _toElementFinisherExtras (app.js:46283)
    at _decorateElement (app.js:46273)
    at app.js:46269
    at Array.forEach (<anonymous>)
    at _decorateClass (app.js:46269)
    at _decorate (app.js:46251)
    at Module../src/App/stores/UserStore.js (app.js:46301)
    at __webpack_require__ (bootstrap:19)
    at Module../src/App/stores/index.js (index.js:1)

这是我的UserStore.js文件:

import { 
  configure,
  runInAction,
  observable,
  action,
  computed
} from 'mobx'
import API from '../api'

configure({ enforceActions: 'observed' })

class UserStore {
  @observable users
  @observable state
  @observable currPage
  @observable hasMore
  @observable errors

  constructor() {
    this.users = []
    this.state = 'loading'
    this.currPage = 0
    this.hasMore = true
    this.errors = []
  }

  @action
  addUser = (user) => {
    this.users.shift(user)
  }

  @action
  addUsers = (users) => {
    this.users = this.users.concat(users)
  }

  @action
  async fetchUsers () {
    let req;
    try {
      req = await API.allUsers()
      runInAction(() => {
        this.state = 'done'
        this.addUsers(req.body.users || [])
        this.hasMore = (req.body.users && req.body.users.length) ? true : false
        this.currPage = this.currPage + 1
      })
    } catch (e) {
      runInAction(() => {
        this.state = 'error'
        this.hasMore = false
      })
    }
  }

  @computed
  get females () {
    return this.users.filter(user => user.gender === 'female')
  }

  @computed
  get males () {
    return this.users.filters(user => user.gender === 'male')
  }
}

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

如果我删除@computed应用程序负载。

标签: babeljsmobx

解决方案


我的错误的原因是.babelrcBabel 7 的配置不正确。

失败

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    [ "@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": true } ],
    "transform-class-properties",
    "@babel/plugin-transform-runtime"
  ]
}

在职的

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    [ "@babel/plugin-proposal-decorators", { "legacy": true } ],
    [ "@babel/plugin-proposal-class-properties", {
      "loose": true
    }],
    "@babel/plugin-transform-runtime"
  ]
}

推荐阅读