Skip to content
← Back to rules

react/no-unsafe 正确性

它做了什么

此规则识别并限制使用不安全的 React 生命周期方法。

为什么这是个问题?

某些生命周期方法(componentWillMountcomponentWillReceivePropscomponentWillUpdate)被认为不安全,并自 React 16.9 起已被弃用。它们经常被误用,导致在异步渲染中出现问题。应避免使用带有 UNSAFE_ 前缀的版本或已弃用的方法名称本身。

示例

以下为 错误 的代码示例:

jsx
// 默认情况下,带有 UNSAFE_ 前缀的方法会被标记
class Foo extends React.Component {
  UNSAFE_componentWillMount() {}
  UNSAFE_componentWillReceiveProps() {}
  UNSAFE_componentWillUpdate() {}
}

// 当 checkAliases: true 时,非前缀版本也会被标记
class Bar extends React.Component {
  componentWillMount() {}
  componentWillReceiveProps() {}
  componentWillUpdate() {}
}

以下为 正确 的代码示例:

jsx
class Foo extends React.Component {
  componentDidMount() {}
  componentDidUpdate() {}
  render() {}
}

配置

此规则接受一个包含以下属性的配置对象:

checkAliases

type: boolean

default: false

是否检查非前缀的生命周期方法。
若为 true,则不仅会标记 UNSAFE_ 版本,还会标记 componentWillMountcomponentWillReceivePropscomponentWillUpdate 这些未加前缀的形式。建议将其设为 true,以彻底避免使用不安全的生命周期方法。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-unsafe": "error"
  }
}
bash
oxlint --deny react/no-unsafe --react-plugin

参考资料