错误:不变式失败:你不应在 <Router> 外部使用 <Link>
Error: Invariant failed: You should not use <Link> outside a <Router>
ID: react/invariant-failed-router-outside
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React Router v5.x | active | — | — | — |
| React Router v6.x | active | — | — | — |
| React 16.8+ | active | — | — | — |
| React 18.x | active | — | — | — |
根因分析
React Router 组件(例如 Link、NavLink、useNavigate)在 Router 上下文提供程序外部使用,通常是由于组件树中缺少或顺序错误的 Router 包装器。
English
A React Router component (e.g., Link, NavLink, useNavigate) is used outside of a Router context provider, typically due to missing or misordered Router wrapper in the component tree.
官方文档
https://reactrouter.com/en/main/router-components/browser-router解决方案
-
在顶层用 Router(例如 BrowserRouter)包裹你的应用或相关组件树。示例:import { BrowserRouter } from 'react-router-dom'; function App() { return (<BrowserRouter><YourRoutes /></BrowserRouter>); } -
如果使用嵌套路由,确保每个路由的组件可以访问路由器上下文;避免在不在 Route 或 Router 内部的组件中渲染 Link。
-
对于测试,用 MemoryRouter 或 StaticRouter 包裹组件以提供路由上下文。示例:render(<MemoryRouter><Link to='/'>Home</Link></MemoryRouter>);
无效尝试
常见但无效的做法:
-
Importing Router from 'react-router' instead of 'react-router-dom'.
70% 失败
React Router v5+ has separate packages; the Router component is in 'react-router-dom' for web apps, and using the wrong import may not provide the correct context.
-
Wrapping only the Link component with a Router, but leaving other parts of the app outside.
80% 失败
The Router must wrap the entire part of the tree that uses routing; partial wrapping can cause other routing components (like useParams) to fail.
-
Using BrowserRouter but forgetting to install 'react-router-dom' and relying on a global script.
90% 失败
Without proper npm installation, the import may fail or resolve to a different version, leading to context mismatch.