React内存泄漏与typescript使用谷歌firestore和React路由器



我目前正在使用firestore,但我目前遇到了内存泄漏的问题,因为我在离开屏幕前以事务方式删除了我的组件。避免这种泄漏的最佳方法是什么当我点击链接组件时,我想从数据库中删除通知,它似乎可以工作并将我带到新页面,唯一的问题是内存泄漏我该如何避免这种情况。

const loadAlerts = useCallback(() => {
const alertNotifcationsObserver = onSnapshot(notifications, (querySnapshot) => {
const alertData: any[] = []
querySnapshot.forEach((doc) => {
console.log(doc.data())
alertData.push({
...doc.data(),
doc
})
});
setAlertNotifcations(alertData)
});
return alertNotifcationsObserver
}, [notifications])

useEffect(() => {
loadAlerts();
console.log(alertNotifications)
}, []);

<IonItem onClick={async (e) => {
console.log(i.Reference)
await  notificationsController(i.Reference)
}} key={i.Reference} lines='full'>
<Link
to={{
pathname: i.Link,
state: { documentReferencePath: i.Reference }
}}
>
{i.Type}
</Link>
</IonItem>

const notificationsController = async(documentReferencePath:string)=>{

try {
await runTransaction(db, async (transaction) => {
const documentReference =  doc(db,documentReferencePath)
const notificationDoc = await transaction.get(documentReference);
if (!notificationDoc.exists()) {
throw "Document does not exist!";
}
transaction.delete(documentReference)
});
console.log("Notification removed successfully committed!");
} catch (e) {
console.log("Transaction failed: ", e);
}
index.js:1 Warning: 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.

我该如何消除这个错误我还试图为loadAlerts添加取消订阅,但类型脚本也给了我一个错误。

Argument of type '() => () => Unsubscribe' is not assignable to parameter of type 'EffectCallback'.

您似乎不太可能在useEffect钩子外或任何其他回调中调用loadAlerts函数,将其移动到useEffect钩子中以将其作为依赖项删除,并从useEffect返回一个清除函数以取消订阅。

useEffect(() => {
const unsubscribe = onSnapshot(
notifications,
(querySnapshot) => {
const alertData: any[];
querySnapshot.forEach((doc) => {
alertData.push({
...doc.data(),
doc,
});
});
setAlertNotifcations(alertData);
});
return unsubscribe;
}, []);

最新更新