防止:查询进行时存储重置(未在链接链中完成)

its*_*old 7 apollo apollostack react-apollo apollo-client

我在我的 Apollo Client 代码中随机得到了这个。我正在使用使用 isMounted 标志包围所有 setState 的反模式,以防止在卸载组件或用户离开页面时尝试设置状态。但我仍然得到这个

Store reset while query was in flight (not completed in link chain)
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?

小智 0

有点死气沉沉的帖子,但如果您致电 ,这种情况经常发生client.resetStore(),不幸的是,这是 Apollo 文档在搜索有关如何注销的最佳实践时的第一个建议。

如果您在尝试实施他们的解决方案时遇到此问题,请注意他们的文档进一步提到这resetStore将导致重新获取所有活动查询。如果您随后进行了重新渲染,导致第二次调用resetStore,则您将在查询正在进行时重置存储,从而导致此错误。

我为解决这个问题做了以下几件事:

  1. 不要使用resetStore. 使用clearStore(如果您不打算重新获取查询,他们的文档建议这样做)
  2. 对注销机制实施某种幂等性控制。作为一个天真的例子
const AuthenticatedComponent = () => {
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const client = useApolloClient();
  
  const logout = () => {
    if (!isLoggingOut) {
      // or whatever business logic you use to invalidate session
      deleteSession(); 
      client.clearStore();
      setIsLoggingOut(true);
    }
  };
  return (<>
    { /* Whatever else */ }
    <button onClick={logout}> Log Out </button>
  </>)
}
Run Code Online (Sandbox Code Playgroud)