reactjs / reactjs/react.dev

Using fetch in useEffect and checking if the component is mounted before setting state

未关闭
#2,823 0 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

@gaearon 已经在做这个了。

开始于 2020年3月11日。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

Consider the following code:

const useIsMounted = () => {
  const isMounted = React.useRef(false);
  React.useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);
  return isMounted;
};

And the effect:

const [result, setResult] = React.useState({
  loading: true,
  data: []
})
const isMounted = useIsMounted();
React.useEffect(() => {
    console.log('in effect')
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then(result => result.json())
      .then(data => {
        //before setting state in async function you should
        //  check if the component is still mounted
        isMounted.current && setResult({ loading: false, data })
      })
  },[isMounted])

This code will start a discussion about this being an anti pattern. I think that it's comparing apples with oranges and that article does not apply here.

The useEffect clean up examples show a situation where variables in the callback's closure don't go out of scope and can cause a memory leak but the fetch example won't have that problem.

Is it possible to provide examples of how to safely combine setting state with asynchronous fetch result while not setting it on unmounted components?

It is possible to cancel a fetch (maybe in all browser with the correct babel configuration) but when using SSR (like next.js) and using something like isomorphic-fetch then this is not an option.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。