为什么将观察者添加到 react-query 会导致它忽略其“已启用”属性?

Why does adding an observer to react-query cause it to ignore its `enabled` property?

更新:我现在已经将此作为问题提交到 react-query 的 Github,你可能应该关注它 there.

我有一个非常简单的 useQuery:

const refreshable = false // hard coded for the sake of example
const tokenQuery = useQuery('refresh-token', refreshQueryFn, {
  enabled: refreshable,
  refetchInterval: 1000 * 30,
  refetchIntervalInBackground: true,
})

如果这是独立的则没有问题。一切都初始化,除非设置 refreshable true 然后它处于休眠状态。

但是,在同一个钩子中我添加了一个观察者...

useEffect(() => {
  // Create an observer to watch the query and update its result into state
  const observer = new QueryObserver(queryClient, {
    queryKey: 'refresh-token',
  })
  const unsubscribe = observer.subscribe((queryResult) => {
    console.log(
      'Do something with the token!'
      queryResult.data
    )
  })

  // Clean up the subscription when the component unmounts
  return () => {
    unsubscribe()
  }
}, [token, queryClient])

无论enabled如何,附加观察者都会导致获取(以及失败和多次重试)发生,我认为这不应该发生。

在我提出关于 react-query 的问题之前,谁能解释为什么会这样?

在幕后,useQuery 使用您传递给它的选项创建了一个 QueryObserver。所以在 userQuery 之后,你将有一个观察者启用:false,这会给你一个禁用的查询。

现在启用了每个观察者 属性。启用一个 useQuery 实例而禁用另一个具有相同 queryKey 的实例是完全合法的。

这基本上就是您正在做的事情:当您手动创建新的 QueryObserver 时,您没有将 enabled: false 传递给它,因此您创建了第二个已启用的观察器,然后它将 运行查询。

因此将 refreshable 传递给新的 Oberver 的 enabled 选项应该可以解决它:

const observer = new QueryObserver(queryClient, {
  queryKey: 'refresh-token',
  enabled: refreshable,
})