Skip to content
← Back to rules

react/no-direct-mutation-state 正しさ

何を実行するか

このルールは、React コンポーネント内で this.state を直接変更することを禁止します。

注釈:このルールはクラスコンポーネントにのみ適用され、関数コンポーネントには適用されません。現代的な React プロジェクトでは、このルールは不要または無関係な場合があります。

なぜ問題なのか

React コンポーネントは 絶対に this.state を直接変更してはいけません。なぜなら、その後 setState() を呼び出すと、あなたが行った変更が上書きされる可能性があるからです。

this.state は不可変であるかのように扱うべきです。

このルールに違反する 誤った 例:

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

class Hello extends React.Component {
  constructor(props) {
    super(props);

    doSomethingAsync(() => {
      this.state = "bad";
    });
  }
}

このルールに準拠する 正しい 例:

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

class Hello extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      foo: 'bar',
    }
  }
}

使い方

設定ファイルまたは CLI でこのルールを 有効化 するには、次のように使用できます:

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

参照