今日の日付をで初期化した状態に設定する関数にインターバルタイマーを設定していますcomponenteDidMount
。の間隔をクリアしましたがcomponentWillUnmount
、コンポーネントをすばやく切り替えた後でもエラーが発生します(これがバグを見つけた方法です)。
これはエラーです:
警告: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
_isMounted
サイクル全体でプライベート変数をfalseからtrueに操作し、setTodaysDate()
状態を設定する前に条件付きチェックを強制しようとしましたが、それでも問題は解決しませんでした。
// _isMounted = false; <----- tried this method to no avail
state = {
selectedDate: ""
};
componentDidMount() {
this.setTodaysDate();
this.interval = setInterval(() => this.setTodaysDate(), 40 * 1000 * 360);
// this._isMounted = true; <----- tried
}
componentWillUnmount() {
clearInterval(this.interval);
// this._isMounted = false; <----- tried
}
setTodaysDate = () => {
// if (this._isMounted) { <----- tried
this.setState({
selectedDate: moment(moment(), "YYYY-MM-DDTHH:mm:ss")
.add(1, "days")
.format("YYYY-MM-DD")
});
// } <----- tried
}
他に「漏れを塞ぐ」方法がわからない。
編集:以下のGabrieleのおかげで、本当の原因は、アンマウント中にキャンセルしたことがなく、「リーク」につながる、使用していたlodashデバウンスメソッド(setStateも使用)でした。
debounceCloseAlert = _.debounce(() => {
this.setState({ alertVisible: false });
}, 5000);
あなたのコンポーネントを見て、私は問題があなたにあるとは思わないsetInterval
。それを処理する方法は正しいアプローチであり、上記のエラーを生成するべきではありません。
私が信じる問題_.debounce
はあなたのdebounceCloseAlert
方法での使用にあります。また、タイムアウトが発生し、どこでもそれをクリアしていません。
からの戻り値に_.debounce
は.cancel()
、間隔をクリアするメソッドが含まれています。だからthis.debounceCloseAlert.cancel();
あなたcomponentWillUnmount
を呼ぶだけでそれはクリアされます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加