mobx 6中装饰器函数的移除

1,852 阅读2分钟

装饰器函数的移除

mobx 6 放弃的装饰器语法的使用,移除了装饰器函数的语法,转而使用了 makeObservable 或者 makeAutoObservable 函数将实例的属性转换为 observable

mobx 6 前后的使用对比

mobx 6 之前

import { action, observable } from "mobx"

class CounterStore {
  @observable count = 0

  @action.bound increment () {
    this.count++
  }

  @action.bound decrement () {
    this.count--
  }
}

const counterStore = new CounterStore()

export default counterStore

mobx 6

import { action, makeObservable, observable } from "mobx"

class CounterStore {
  count = 0

  constructor () {
    makeObservable(this, {
      count: observable,
      increment: action.bound,
      decrement: action.bound
    })
  }

  increment () {
    this.count++
  }

  decrement () {
    this.count--
  }
}

const counterStore = new CounterStore()

export default counterStore

通过上面代码的对比可以看出,mobx 6 中已经彻底抛弃了之前装置器的使用方式。装饰器语法在 js 标准中是一个不稳定的语法,vue3 在开发过程中也因需要使用到装饰器而放弃使用类语法来开发,转而投向函数的怀抱。

虽然 mobx 6 已经移除了装饰器函数,但是因为网上的许多教程都依然还是以前的写法,因此 mobx 6 兼容装饰器的写法,但是必须在 constructor 中调用 makeObservable 或者 makeAutoObservable 函数。

import { action, observable, makeObservable } from "mobx"

class CounterStore {
  constructor () {
    makeObservable(this, {
      count: observable,
      increment: action.bound,
      decrement: action.bound
    })
  }
  
  @observable count = 0

  @action.bound increment () {
    this.count++
  }

  @action.bound decrement () {
    this.count--
  }
}

const counterStore = new CounterStore()

export default counterStore

装饰器的语法在列入标准之前还有很长的一段时间,官方也建议不要使用装饰器的方式进行开发。虽然我也觉得装饰器的语法很好用,相比 mobx 6 中的方式,装饰器的使用时较为方便。但是装饰器毕竟是一种不成熟的方案,所以在项目开发中建议还是不要使用装饰器。而在 mobx-react 中的装饰器不仅可以通过装饰的方式使用,同时也是一个函数,可以直接被调用

mobx-react 使用方式

装饰器的使用

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';

@inject("counter")
@observer
class App extends Component {
  render () {
    const { counter } = this.props
    return (
      <div>
        <button onClick={ this.props.counter.increment }>+</button>
        <span>{ counter.count }</span>
        <button onClick={ counter.decrement }>-</button>
      </div>
    )
  }
}

export default App;

函数的使用

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render () {
    const { counter } = this.props
    return (
      <div>
        <button onClick={ this.props.counter.increment }>+</button>
        <span>{ counter.count }</span>
        <button onClick={ counter.decrement }>-</button>
      </div>
    )
  }
}

export default inject('counter')(observer(App));

官方文档

更多的细节,可以查看官方的文档

mobx 5 文档
mobx 6 文档