清理功能第一次使用 AbortController 失败
Cleanup function fails the first time using AbortController
我正在使用 AbortController
取消卸载 React 生命周期的 fetch
承诺。
出于某种原因,清理 在元素卸载的第一时间不工作 。
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]);
按照以下步骤操作:
- 访问演示 link。
- 快速单击
Show/hide pokemon
按钮两次以强制中止 子 Pokemon
反应元素。
- 检查控制台错误:
Can't perform a React state update on an unmounted component
- 重复步骤 2。快速单击
Show/hide pokemon
按钮两次以强制中止 子 Pokemon
反应元素。
- 这次没有发现错误,随后重试。为什么?
Note: When abort()
is called, the fetch()
promise rejects with a
DOMException
named AbortError
.
当组件卸载并调用 abort
时,fetch
会因错误而拒绝。错误被捕获并且此代码正在尝试设置错误状态。省略此错误状态更新会删除反应错误。
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]);
我也愿意打赌错误发生 每次 但反应只是输出第一个并为后续错误输出静音。
我正在使用 AbortController
取消卸载 React 生命周期的 fetch
承诺。
出于某种原因,清理 在元素卸载的第一时间不工作 。
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]);
按照以下步骤操作:
- 访问演示 link。
- 快速单击
Show/hide pokemon
按钮两次以强制中止 子Pokemon
反应元素。 - 检查控制台错误:
Can't perform a React state update on an unmounted component
- 重复步骤 2。快速单击
Show/hide pokemon
按钮两次以强制中止 子Pokemon
反应元素。 - 这次没有发现错误,随后重试。为什么?
Note: When
abort()
is called, thefetch()
promise rejects with aDOMException
namedAbortError
.
当组件卸载并调用 abort
时,fetch
会因错误而拒绝。错误被捕获并且此代码正在尝试设置错误状态。省略此错误状态更新会删除反应错误。
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]);
我也愿意打赌错误发生 每次 但反应只是输出第一个并为后续错误输出静音。