在我们的代码库中,我发现了一个自定义钩子,它执行如下异步请求:
export const useGetPlayersByTeamId = () => {
const [data, setData] = useState({});
const {
processErrorResponse,
errorNotification,
} = useResponse();
const fetchData = useCallback(async (teamId) => {
if (teamId) {
try {
const teamSvc = new TeamService();
const players = await teamSvc.getPlayersByTeamId(
teamId
);
if (players) {
setData(players);
} else {
errorNotification('An error occurred while loading players');
}
} catch (error) {
processErrorResponse({ error });
}
}
}, [processErrorResponse, errorNotification]);
return [data, fetchData];
};
我最近注意到在卸载组件时尝试更新状态 (setData(players)
) 导致的一些错误消息:
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.
我检查了 this post 并尝试将通过 useCallback
的记忆与 useEffect
中的实际数据提取分开,但我有点困惑,因为所有这些都发生在自定义钩子而不是实际组件。后者期望返回数组,所以老实说我不明白如何在这种情况下应用相同的概念。
这里的目标是,如果用户在第一个承诺解决之前点击团队 A,然后点击团队 B,则返回团队 B 的球员。