Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: migrating-from-4-or-5.md #73

Merged
merged 6 commits into from
Jun 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 38 additions & 39 deletions docs/migrating-from-4-or-5.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,73 @@
---
title: Migrating from MobX 4/5
sidebar_label: Migrating from MobX 4/5 {🚀}
title: 从MobX 4/5迁移
sidebar_label: 从MobX 4/5迁移 {🚀}
hide_title: true
---

<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CEBD4KQ7&placement=mobxjsorg" id="_carbonads_js"></script>

# Migrating from MobX 4/5 {🚀}
# 从MobX 4/5迁移 {🚀}

MobX 6 is quite different from MobX 5. This pages covers a migration guide from MobX 4 and 5 to 6, and an extensive list of all the changes.
MobX 6与MobX 5有很大的不同。这一页涵盖了从MobX 4/5到6的迁移指南和所有更改的详细列表。

For a better understanding, check out the MobX 6.0 [CHANGELOG](https://github.com/mobxjs/mobx/blob/main/packages/mobx/CHANGELOG.md#600).
为了更好地理解,请查看MobX 6.0 [CHANGELOG](https://github.com/mobxjs/mobx/blob/main/packages/mobx/CHANGELOG.md#600).

_⚠️ **Warning**: Depending on factors like the size and complexity of your code base, your MobX usage patterns, and the quality of your automated tests, this migration guide might take you anywhere between an hour and a couple of days. Please refrain from upgrading if you don't trust your Continuous Integration or QA / test procedures enough to pick up any unexpected breakages. Unexpected behavioral changes might be caused by changes in MobX itself or the changes needed to your Babel / TypeScript build configuration. ⚠️_
_⚠️ **警告**: 根据你的代码库的大小和复杂性、MobX使用模式和自动化测试的质量等因素,本迁移指南可能会耗费你一小时到几天的时间。如果你对你的持续集成没有信心或者无法有足够的QA /测试应对任何意外的故障,请避免升级。意想不到的行为变化可能是由于MobX本身的变化或者Babel / TypeScript构建配置的变化引起的。 ⚠️_

## Getting started
## 开始

1. Update `mobx` to the latest version of MobX 4/5 and solve any deprecation messages.
2. Update `mobx` to version 6.
3. If you are upgrading from MobX 4, and you will need to support Internet Explorer / React Native without proxies, call `import { configure } from "mobx"; configure({ useProxies: "never" })` at the initialization of your application, to back-out of the Proxy implementation. Check out the [Proxy Support](configuration.md#proxy-support) section for more details.
4. For babel users:
- If you are using Babel and have class-properties enabled, disable the legacy loose field support: `["@babel/plugin-proposal-class-properties", { "loose": false }]`
- (Optional) In MobX 6 decorators have become opt-in. If you no longer wish to use decorators, remove `plugin-proposal-decorators` from your babel configuration and dependencies. Check out the [Enabling decorators {🚀}](enabling-decorators.md) section for more details.
5. For Typescript users:
- Add the flag `"useDefineForClassFields": true` to your compiler config.
- (Optional) In MobX 6 decorators have become opt-in. If you no longer wish to use decorators, remove / disable the `experimentalDecorators` configuration from your TypeScript config. Check out the [Enabling decorators {🚀}](enabling-decorators.md) section for more details.
6. The MobX default configuration has become more strict. We recommend to adopt the new defaults after completing the upgrade, check out the [Configuration {🚀}](configuration.md) section. During migration, we recommend to configure MobX in the same way as it would be in v4/v5 out of the box: `import {configure} from "mobx"; configure({ enforceActions: "never" });`. After finishing the entire migration process and validating that your project works as expected, consider enabling the flags `computedRequiresReaction`, `reactionRequiresObservable` and `observableRequiresReaction` and `enforceActions: "observed"` to write more idiomatic MobX code.
1. `mobx`更新到mobx 4/5的最新版本,并处理所有弃用消息。
2. `mobx`更新到版本6。
3. 如果你从Mobx 4升级,并且需要兼容不支持Proxy的IE / React Native,请在应用初始化时引入`import { configure } from "mobx"; configure({ useProxies: "never" })`以禁用Proxy实现。 查看 [Proxy Support](configuration.md#proxy-support) 章节以了解更多细节
4. 对于babel用户:
- 如果你正在使用Babel并启用了类属性,那么请禁用loose字段: `["@babel/plugin-proposal-class-properties", { "loose": false }]`
- (可选) 在MobX 6中,decorators已经变为可选项。如果你不想再使用decorators,从你的babel配置和dependencies中移除`plugin-proposal-decorators`。 查看 [Enabling decorators {🚀}](enabling-decorators.md) 章节以了解更多细节。
5. 对于Typescript用户:
- 在你的编译器配置中添加`"useDefineForClassFields": true`
- (可选) 在MobX 6中,decorators已经变为可选项。 如果你不想再使用decorators,在你的TypeScript配置中移除或者禁用`experimentalDecorators`。 查看 [Enabling decorators {🚀}](enabling-decorators.md) 章节以了解更多细节。
6. MobX默认配置变得更加严格。 我们建议在完成升级后采用新的默认值,查看 [Configuration {🚀}](configuration.md) 章节。 在迁移过程中,我们建议以v4/v5开箱即用的相同方式配置MobX: `import {configure} from "mobx"; configure({ enforceActions: "never" });`。 在完成整个迁移过程并确认您的项目按预期工作之后,请考虑启用`computedRequiresReaction``reactionRequiresObservable``observableRequiresReaction`以及`enforceActions: "observed"`来编写更符合MobX习惯的代码。

## Upgrading classes to use `makeObservable`
## 升级类以使用`makeObservable`

Due to standardized JavaScript limitations in how class fields are constructed, it is no longer possible for MobX to alter the behavior of class fields by means of decorators or the `decorate` utility. Instead, fields have to be made observable by the `constructor`. This can be done in three different ways:
由于标准化的JavaScript在如何构造类字段方面的限制,MobX不再可能通过装饰器或`decorate`工具来改变类字段的行为。作为代替,字段必须通过`constructor`定义为observable。有三种不同的实现方式:

1. Remove all decorators and call `makeObservable` in the `constructor` and explicitly define which field should be made observable using which decorator. For example: `makeObservable(this, { count: observable, tick: action, elapsedTime: computed })` (note that the second argument corresponds to what would be passed to `decorate`). This is the recommended approach if you want to drop decorators in your code base, and the project isn't yet too big.
2. Leave all the decorators and call `makeObservable(this)` in the `constructor`. This will pick up the metadata generated by the decorators. This is the recommended way if you want to limit the impact of a MobX 6 migration.
3. Remove decorators and use `makeAutoObservable(this)` in the class `constructor`'s.
1. 移除所有的decorators,并在`constructor`中调用`makeObservable`,并显式地使用对应decorator定义哪个字段应该成为observable。比如: `makeObservable(this, { count: observable, tick: action, elapsedTime: computed })` (注意,第二个参数是传递给`decorate`的内容)。 如果您想在代码库中去掉decorators,并且项目还不是太大,那么推荐使用这种方法。
2. 保留所有的decorators,并在`constructor`中调用`makeObservable(this)`。 这将获取装饰器生成的元数据。如果你想要限制MobX 6迁移的影响,那么推荐使用这种方法。
3. 移除decorators,并在类的`constructor`中调用`makeAutoObservable(this)`

Check out [makeObservable / makeAutoObservable](observable-state.md) for more details.
查看 [makeObservable / makeAutoObservable](observable-state.md) 以了解更多细节.

Some specifics to note:
需要注意的一些细节:

1. Using `makeObservable` / `makeAutoObservable` needs to be done in every class definition that declares MobX based members. So if a sub-class and super-class both introduce observable members, they will both have to call `makeObservable`.
2. `makeAutoObservable` will mark methods using a new decorator `autoAction`, that will apply `action` only if it is not in a derivation context. This makes it safe to call automatically decorated methods also from computed properties.
1. 在每个声明MobX的基础成员的类定义中都需要使用`makeObservable` / `makeAutoObservable`。 因此,如果子类和超类都引入了observable成员,它们都必须调用`makeObservable`
2. `makeAutoObservable`将使用新的装饰器`autoAction`标记方法,只有当方法不在 derivation context 时,它才会应用`action`。这使得从计算属性中调用自动装饰的方法也很安全。

Migrating a large code base with lots of classes might be daunting. But no worries, there is a code-mod available that will automate the above process!!
迁移带有许多类的大型代码库可能是令人生畏的。但是不用担心,有一个code-mod可以自动完成上述过程!!

## Upgrading your code with the `mobx-undecorate` codemod
## 使用`mobx-undecorate` codemod 升级你的代码

If you are an existing MobX user you have code that uses a lot of decorators, or the equivalent calls to `decorate`.
如果你是一个现有的MobX用户,你的代码使用了许多decorators,或者对`decorate`的等效调用。

The [`mobx-undecorate`](https://www.npmjs.com/package/mobx-undecorate) package provides a codemod that can automatically update your code to be conformant to MobX 6. There is no need to install it; instead you download and execute it using the [`npx`](https://www.npmjs.com/package/npx) tool which you do need to install if you haven't already.
[`mobx-undecorate`](https://www.npmjs.com/package/mobx-undecorate) 包提供了一个codemod可以自动更新你的代码,使其更加符合MobX 6。此包无需安装;你只需要下载并使用[`npx`](https://www.npmjs.com/package/npx) 工具,如果没有npx工具你必须首先安装。

To get rid of all uses of MobX decorators and replace them with the equivalent `makeObservable` calls, go to the directory that contains your source code and run:
如果要弃用所有MobX装饰器的使用,并将它们替换为等效的`makeObservable`调用,请转到包含源代码的目录并运行:

```shell
npx mobx-undecorate
```

MobX will continue to support decorators -- so if you want to retain them
and only introduce `makeObservable(this)` where required, you can use the `--keepDecorators` option:
MobX会继续支持装饰器语法 -- 因此若你想保留它们并只在需要的地方引入`makeObservable(this)`,你可以使用`--keepDecorators`选项:

```shell
npx mobx-undecorate --keepDecorators
```

See [documentation](https://www.npmjs.com/package/mobx-undecorate) for more options.
查看 [documentation](https://www.npmjs.com/package/mobx-undecorate) 以了解更多选项。

### Limitations of `mobx-undecorate`
### `mobx-undecorate`的局限性

The `mobx-undecorate` command has to introduce a constructor in classes that do not yet have one. If base class of the constructor expects arguments, the codemod cannot introduce these arguments for the subclass being upgraded, and the `super` call won't pass them either. You have to fix these manually.
The tool will generate a `// TODO: [mobx-undecorate]` comment in these cases.
`mobx-undecorate`命令必须在还没有构造函数的类中引入构造函数。如果构造函数的基类需要参数,则codemod不能为需要升级的子类引入这些参数,而`super`调用也不会传递它们。 你必须手动修复这些问题。
在这些情况下,该工具将生成`// TODO: [mobx-undecorate]`注释。

We do have a special case for React class components to do the right thing and
pass along `props` to the superclass.
我们确实有一个React类组件做正确事情的特殊情况
通过`props`传递给超类。