Skip to content
← Back to rules

react/no-did-mount-set-state 正确性

它的作用

禁止在 componentDidMount 生命周期方法中使用 setState

该规则对函数组件不适用,因此在现代 React 项目中可能可以禁用。

为什么这是问题?

在组件挂载后更新状态会触发第二次 render() 调用,可能导致属性/布局抖动。 这可能会引发性能问题和意外行为。

示例

以下为 错误 用法示例:

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    this.setState({
      name: this.props.name.toUpperCase(),
    });
  },
  render: function () {
    return <div>Hello {this.state.name}</div>;
  },
});

以下为 正确 用法示例:

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    this.onMount(function callback(newName) {
      this.setState({
        name: newName,
      });
    });
  },
  render: function () {
    return <div>Hello {this.state.name}</div>;
  },
});

配置

此规则接受以下字符串值之一:

"allowed"

允许在 componentDidMount 内部嵌套函数中调用 setState,这是默认行为。

"disallow-in-func"

启用后,也禁止在 componentDidMount 内部嵌套函数中调用 setState

如何使用

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

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-did-mount-set-state": "error"
  }
}
bash
oxlint --deny react/no-did-mount-set-state --react-plugin

参考资料