使用useQuery时触发Invalid hook call错误的排查求助
React Hook调用报错(Invalid hook call)排查与解决
问题场景
我编写了如下useQuery调用用于获取示例数据:
import {Weather} from "../../Models/Weather/Weather"; import axios from "axios"; import {useQuery} from "react-query"; export const getWeatherForecastKey = () => "weather"; export const useWeatherForecast = () => useQuery<Weather[]>(getWeatherForecastKey(), () => axios .get( `https://localhost:44471/api/weatherforecast` ) .then((response) => response.data) );
并在RegisterPage页面中调用该自定义hook:
import React from 'react'; import {useWeatherForecast} from "../../Hooks/queries/useWeatherForecast"; const RegisterPage: React.FunctionComponent = () => { const {data: weather, isLoading: isLoadingWeather, isError: isErrorWeather} = useWeatherForecast(); if(isLoadingWeather) return <h1>Loading...</h1> if(!weather || isErrorWeather) return <h1>Error...</h1> return ( <div> <h1 id="tableLabel">Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> </div> ); }; export default RegisterPage;
RegisterPage通过如下路由配置使用:
const AppRoutes = [ { path: '/register', element: <RegisterPage /> } ]; export default AppRoutes;
移除页面中的hook调用时,RegisterPage可以正常加载,但保留hook时始终触发Invalid hook call错误。
可能的原因及解决办法
React Query未配置上下文(最可能的原因)
React Query的所有Hook必须在QueryClientProvider的上下文环境中使用,否则会直接抛出Hook调用错误。在应用根组件(如App.tsx或main.tsx)中添加全局配置:import { QueryClient, QueryClientProvider } from 'react-query'; import AppRoutes from './path/to/AppRoutes'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <AppRoutes /> </QueryClientProvider> ); } export default App;依赖版本不兼容
确保react-query版本与项目中react、react-dom版本匹配:react-queryv3要求React 16.8+react-queryv4要求React 17+
可重新安装适配版本:
npm uninstall react-query # 以v3为例,安装兼容版本 npm install react-query@3重复安装依赖
检查项目是否存在多份React或React Query依赖(如子目录也有node_modules),删除后重新安装:rm -rf node_modules package-lock.json npm installHook调用违反规则
确认useWeatherForecast仅在React函数组件或自定义Hook的顶层调用,未在条件判断、循环或嵌套函数内执行。
内容的提问来源于stack exchange,提问作者m_novak
相关产品推荐
相关产品推荐

