react/no-unsafe Correctness
功能说明
此规则用于识别并限制不安全的 React 生命周期方法的使用。
为什么这很糟糕?
某些生命周期方法(componentWillMount、componentWillReceiveProps 和 componentWillUpdate) 被视为不安全,并且自 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,则表示 componentWillMount、componentWillReceiveProps 和 componentWillUpdate 也会被标记,而不仅仅是 UNSAFE_ 版本。建议将其设置为 true,以彻底 避免不安全的生命周期方法。
使用方法
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-unsafe": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-unsafe": "error",
},
});bash
oxlint --deny react/no-unsafe --react-plugin版本
此规则在 v1.35.0 中添加。
