簡體   English   中英

清理 function 第一次使用 AbortController 失敗

[英]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]);

演示

請按照以下步驟操作:

  1. 訪問演示鏈接。
  2. 快速單擊Show/hide pokemon按鈕 TWICE 以強制中止Pokemon反應元素。
  3. 檢查控制台中的錯誤: Can't perform a React state update on an unmounted component
  4. 重復步驟 2。快速單擊Show/hide pokemon按鈕 TWICE 以強制中止Pokemon反應元素。
  5. 這次沒有發現錯誤,隨后重試。 為什么?

中止控制器

注意:abort()被調用時, fetch() promise 會拒絕一個名為AbortErrorDOMException

當組件卸載並調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM