網站首頁 編程語言 正文
react報錯:Can’t perform a React state update on an unmounted component. This is a no-op, but it indica
作者:田本初 更新時間: 2023-10-12 編程語言報錯
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 a useEffect cleanup function.
分析
這是由于請求接口數據加載比較慢,setState還未完成,用戶切換了組件或者切換頁面時候,此時組件已被卸載,仍然嘗試修改組件的狀態所導致的問題。在組件被卸載后,setState動作還在持續,但此時無法使用setState來改變組件的狀態,這會導致React引擎出現內存泄漏警告。
解決
為了解決這個問題,應該在組件卸載時,清除所有的異步任務和訂閱,可以使用useEffect的清理函數來完成這個任務。在清理函數中取消所有正在進行的異步任務。
函數式組件寫法
useEffect(() => {
const fetchData = async () => {
const result = await axios.get('api/data')
setData(result.data)
}
fetchData()
return () => {
// 在組件卸載后取消異步任務
if (source) {
source.cancel('Component unmounted')
}
}
}, [])
類組件寫法
componentWillUnmount() {
this.setState = () => false
}
原文鏈接:https://blog.csdn.net/owo_ovo/article/details/132468119
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-06-23 C#中的小數和百分數計算與byte數組操作_C#教程
- 2022-04-10 Python?tkinter實現計算器功能_python
- 2022-09-06 Python進程管理神器Supervisor詳解_python
- 2022-06-29 Oracle中case?when函數的用法_oracle
- 2022-10-02 Opencv檢測多個圓形(霍夫圓檢測,輪廓面積篩選)_C 語言
- 2022-04-18 Taro 中的 用戶下拉事件,onPullDownRefresh
- 2022-05-22 C語言鏈接屬性的實踐應用_C 語言
- 2021-12-10 時間戳處理的幾種方式
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支