Tanstack ReactQuery报错:未设置QueryClient,排查方案问询
问题:React Query 提示"No QueryClient set, use QueryClientProvider to set one",组件拆分后报错
现象
- 代码中已通过
QueryClientProvider正确包裹根组件,但将IncidentBar拆分到单独文件后触发报错,组件不拆分时运行正常。 - 依赖版本一致,
package.json和lock文件中@tanstack/react-query及相关包均为4.36.1版本。 - 排查后怀疑问题由Webpack配置导致。
相关代码
index.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import IncidentBar from './app/IncidentBar'; const queryClient = new QueryClient(); ReactDOM.render( <QueryClientProvider client={queryClient}> <IncidentBar/> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider>, document.getElementById('app') );
IncidentBar.tsx
import React from 'react' import { useQuery } from '@tanstack/react-query'; import axios from 'axios'; const IncidentBar = () => { const fetchStatus = async () => { const { data } = await axios.get('...data url...'); return data; } const { data: incidentData } = useQuery('incidentStatus', fetchStatus) console.warn(incidentData) return ( <div className="incident-container"> <span className="mt-sm"> <span className="mr-2">Notice:</span> <a href="https://a place you can look at statuses"> error message goes here </a> </span> </div> ) } export default IncidentBar
Webpack核心配置片段
module.exports = (env) => { const isProduction = env?.production ?? false; const config = { resolve: { extensions: ['.tsx', '.ts', '.js', '.jsx', '.json'], fallback: { 'process/browser': require.resolve('process/browser'), } }, optimization: { // ... splitChunks: false, // ... }, // ...其他配置 }; return config; };
原因分析
报错本质是**@tanstack/react-query被Webpack打包出多个实例**:QueryClientProvider使用的是一个实例的上下文,而useQuery调用的是另一个实例的钩子,导致上下文无法共享,最终提示找不到QueryClient。
导致多实例的核心原因:
- Webpack禁用了
splitChunks,不同模块中引入的react-query被分别打包,产生多个副本。 - 模块解析路径不一致,部分导入可能加载了非预期的包副本。
解决方案
1. 强制Webpack使用单一react-query实例
在Webpack的resolve.alias中添加别名,强制所有导入都指向node_modules中的同一个包:
resolve: { extensions: ['.tsx', '.ts', '.js', '.jsx', '.json'], fallback: { 'process/browser': require.resolve('process/browser'), }, alias: { '@tanstack/react-query': path.resolve(__dirname, 'node_modules/@tanstack/react-query'), '@tanstack/query-core': path.resolve(__dirname, 'node_modules/@tanstack/query-core'), '@tanstack/react-query-devtools': path.resolve(__dirname, 'node_modules/@tanstack/react-query-devtools'), } },
2. 启用splitChunks合并第三方依赖
修改Webpack的optimization.splitChunks配置,将node_modules中的依赖打包到同一个vendor chunk中,避免重复打包:
optimization: { // ...其他配置 splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } }, // ...其他配置 },
3. 清理依赖并重新安装
删除node_modules、package-lock.json(或yarn.lock),重新安装依赖确保没有重复或冲突的包:
rm -rf node_modules package-lock.json npm install
4. 检查异步加载模块
如果项目中有代码分割或异步加载的组件,确保这些组件中导入的react-query使用统一路径,避免加载额外实例。
内容的提问来源于stack exchange,提问作者user21122267
相关产品推荐
相关产品推荐

