はじめに
reactでコンポーネントがマウントされたときに、setStateを呼び出しstateを定義する実装をしているときに、
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ComponentA component.
というエラーで詰まったので、解決したときのメモ。
内容
結論
エラー文に書いてある通りで、マウントされていないコンポーネントでsetState()を呼んでいることがダメです。
以下のように、refを使って要素がしっかり更新されたときにsetState()を実行するようにします。
class ComponentA extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
this.hogeHoge();
}
hogeHoge() {
// 以前の処理(あれば)
// ここでdivに付与された「ref="myRef"」が存在するかどうかを確認
if (this.refs.myRef) {
this.setState({
data: hogehoge // hogehogeは、以前の処理で処理された変数とか
});
}
// 以降の処理(あれば)
}
render() {
return (
<div className="hoge" ref="myRef">
</div>
);
}
}
追加したのは、
- setStateを実行する前の条件分(if(this.refs.myRef))
- divのref(ref="myRef")
です。
詳細
はじめは、componentDidMount()時に実行しているのに、なぜ
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ComponentA component.
とエラーが出て、コンポーネントマウントされる前に実行していると出るんだろうと思っていましたが、、、
omponentDidMount()のせいで、stateが変更されてもう一度render()が実行されるからなのか・・・?
よくわからんという状態でした。。。
詳しい理由をご存じの方、ご教示いただければ幸いです。
ひとまず、refsを使ってしっかりマウントされた後をチェックすればエラーを吐かなくなるからいいかと・・・