无法对卸载的组件执行 React 状态更新。无状态

时间:2021-05-08 15:36:40

标签: reactjs apollo-client

让我们暂时假设我知道错误的含义以及通常发生的时间,但现在我不知道反应会抱怨什么。

错误来自这个简单的组件:

export interface PostHandlerOutProps {
  posts: PostFragment[];
}

export interface PostHandlerProps {
  children: (outProps: PostHandlerOutProps) => ReactNode;
  initialPosts?: PostHandlerOutProps['posts'];
}

const PostsHandler: FC<PostHandlerProps> = ({ children, initialPosts = [] }) => {
  const { data } = useQuery<PostsQuery, PostsQueryVariables>(postsQuery);

  return <>{children({ posts: data?.posts || initialPosts })}</>;
};

组件的使用方法如下:

export interface PostsProps {
  initialPosts: PostFragment[];
}

const Posts: FC<PostsProps> = ({ initialPosts }) => {
  return (
      <PostsHandler initialPosts={initialPosts}>
        {({ posts }) => (
          <div>For simplicity sake nothing but I am still getting the error.</div>
        )}
      </PostsHandler>
  );
};

我仍然随机收到此错误:

Warning: 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.
    at PostsHandler (webpack-internal:///./src/components/post/PostsHandler.tsx:20:3)
    at Posts (webpack-internal:///./src/views/admin/Posts.tsx:18:3)

有人知道这里发生了什么吗?这是我应该关心的事情吗?

仅供说明。我需要这种架构,因为 initialPosts 来自服务器端渲染,我需要在客户端替换相同的数据但来自 useQuery,因为它使我能够对突变的 apollo 缓存更新做出反应。

1 个答案:

答案 0 :(得分:0)

好吧,我似乎设法确定了 Apollo 钩子 useQuery 的问题。自从 2019 年开发人员抱怨这个问题,现在看来 Apollo 团队最终会解决它。根据这篇文章:https://github.com/apollographql/apollo-client/issues/7404#issuecomment-776142370 - 他们将使警告静音。加油阿波罗团队!