安装Expo Router依赖后触发Invalid hook call错误求助
解决Expo Router安装后的Invalid Hook Call错误
错误信息如下:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app This error is located at: in ContextNavigator (at ExpoRoot.js:64) in ExpoRoot (at qualified-entry.js:20) in App (created by ErrorOverlay) in ErrorToastContainer (created by ErrorOverlay) in ErrorOverlay (at withDevTools.ios.js:25) in withDevTools(ErrorOverlay) (at renderApplication.js:57) in RCTView (at View.js:116) in View (at AppContainer.js:127) in RCTView (at View.js:116) in View (at AppContainer.js:155) in AppContainer (at renderApplication.js:50) in main(RootComponent) (at renderApplication.js:67), js engine: hermes
以下是针对性解决步骤:
1. 校验依赖版本兼容性
- 确认
expo、react、react-native版本与Expo Router要求匹配(比如Expo Router v2需要Expo SDK 49+,对应react 18.2.0、react-native 0.72.x) - 执行命令查看当前依赖版本:
npm list react react-native expo - 若版本不匹配,执行适配安装:
npx expo install react react-native expo
2. 移除重复的React副本
- 检查是否存在多份React:
npm ls react - 若输出显示多个层级的react,执行以下操作重置依赖:
rm -rf node_modules package-lock.json npm install - 排查第三方依赖是否单独安装了react,确保所有依赖共用项目根目录的react包。
3. 检查Hook使用是否合规
- 确保所有React Hook(包括Expo Router的
useRouter等)都在函数组件顶层调用,禁止在循环、条件判断或嵌套函数内使用。 - 确认没有在类组件中使用Hook,Expo Router仅支持函数组件。
4. 清除缓存
- 清除Expo项目缓存:
npx expo start --clear - 清除Metro缓存(可选):
npx react-native start --reset-cache
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

