最佳答案
我得到了这个错误:
无法对已卸载的组件执行 React 状态更新 但它表明应用程序中存在内存泄漏。要修复, 取消 useEffect 清理中的所有订阅和异步任务 功能。
当开始取数据和卸载组件时,函数尝试更新卸载组件的状态。
解决这个问题的最好方法是什么?
default function Test() {
const [notSeenAmount, setNotSeenAmount] = useState(false)
useEffect(() => {
let timer = setInterval(updateNotSeenAmount, 2000)
return () => clearInterval(timer)
}, [])
async function updateNotSeenAmount() {
let data // here i fetch data
setNotSeenAmount(data) // here is problem. If component was unmounted, i get error.
}
async function anotherFunction() {
updateNotSeenAmount() //it can trigger update too
}
return <button onClick={updateNotSeenAmount}>Push me</button> //update can be triggered manually
}