【发布时间】:2022-01-12 16:12:54
【问题描述】:
我目前正在使用 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'.
【问题讨论】:
标签: reactjs typescript google-cloud-firestore react-hooks