[英]Cleanup function fails the first time using AbortController
我使用AbortController
在卸載 React 生命周期中取消fetch
promise。 出於某種原因,清理在元素 unmounts 的第一次時不起作用。
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
fetch(`https://pokeapi.co/api/v2/pokemon/${name}`, { signal })
.then(sleeper(1)) // Create some latency
.then(res => res.json())
.then(response => {
setData(response);
})
.catch(error => {
setData(error);
});
return () => {
controller.abort();
};
}, [name]);
請按照以下步驟操作:
Show/hide pokemon
按鈕 TWICE 以強制中止子Pokemon
反應元素。Can't perform a React state update on an unmounted component
Show/hide pokemon
按鈕 TWICE 以強制中止子Pokemon
反應元素。注意:當
abort()
被調用時,fetch()
promise 會拒絕一個名為AbortError
的DOMException
。
當組件卸載並調用abort
時, fetch
會因錯誤而拒絕。 錯誤被捕獲,並且此代碼正在嘗試使用錯誤設置 state。 省略此錯誤 state 更新會刪除反應錯誤。
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
fetch(`https://pokeapi.co/api/v2/pokemon/${name}`, { signal })
.then(sleeper(1)) // Create some latency
.then(res => res.json())
.then(response => {
setData(response);
})
.catch(error => {
setData(error); // <-- this is being called after component unmounts!
});
return () => {
controller.abort();
};
}, [name]);
我也願意打賭每次都會發生錯誤,但反應只是輸出第一個錯誤並讓 output 靜音以處理后續錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.