react
runtime_error
ai_generated
true
错误:不变量失败:不应在 <Router> 外部使用 <NavLink>
Error: Invariant failed: You should not use <NavLink> outside a <Router>
ID: react/invariant-failed-you-should-not-use-navlink-outside-a-router
95%修复率
88%置信度
1证据数
2023-11-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React Router 6.20.0 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
| React 19.0.0 | active | — | — | — |
根因分析
React Router 组件(NavLink)在没有被 Router 提供者(BrowserRouter、HashRouter 等)包裹的情况下渲染,通常是由于缺少提供者组件或顺序错误。
English
A React Router component (NavLink) is rendered without being wrapped in a Router provider (BrowserRouter, HashRouter, etc.), typically due to missing or misordered provider components.
官方文档
https://reactrouter.com/en/main/components/nav-link解决方案
-
Wrap your component tree with a Router provider at the root level (e.g., in App.js): `import { BrowserRouter } from 'react-router-dom'; function App() { return <BrowserRouter><YourComponent /></BrowserRouter>; }` -
If using nested routers, ensure only one Router provider wraps the entire app. Remove duplicate Router components.
无效尝试
常见但无效的做法:
-
95% 失败
The error is about missing React context from Router, not DOM structure.
-
85% 失败
NavLink is part of react-router-dom; using wrong import source doesn't provide the Router context.