reactで「Maximum update depth exceeded」エラーが出た時の対処法
2022/02/20
reactで以下のようなエラーが出てハマったので対処法のメモ。
Cannot update during an existing state transition (such as within `render`)
===
Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops
ソースコード(NG)
以下のように、開始ボタンを押すと呼ばれた関数の中でステートを更新するような処理を書いていました。
startCountDown = () => {
this.setState({ timerCount: 45});
...
}
render() {
return (
<div>
<Button variant="primary" onClick={ this.startCountDown() }>開始</Button>
</div>
);
}
原因
reactはstateの状態が変化すると再レンダリングします。 レンダリング⇒startCountDown実行⇒stateの状態変わる⇒レンダリング・・・ の無限ループとして評価されてエラーとなったようです。
対処方法
以下のonclickで関数を呼び出すのではなく、関数を渡すように定義すれば解消しました。
<Button variant=”primary” onClick={ this.startCountDown()}>開始 ↓ <Button variant=”primary” onClick={ () => this.startCountDown()}>開始