首页 > 解决方案 > 无法对未安装的组件执行 React 状态更新。无状态

问题描述

让我们假装一会儿,我知道错误的含义以及通常是什么时候产生的,但现在我不知道反应抱怨什么。

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

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,因为它使我能够对突变的阿波罗缓存更新做出反应。

标签: reactjsapollo-client

解决方案


好的,看来我设法确定了 Apollo hook 的问题useQuery。由于 2019 年开发人员抱怨这个问题,现在看来 Apollo 团队最终会解决这个问题。根据这篇文章:https ://github.com/apollographql/apollo-client/issues/7404#issuecomment-776142370 - 他们会静默警告。布拉沃阿波罗团队!


推荐阅读