# 错误：不变式失败：你不应在 <Router> 外部使用 <Link>

- **ID:** `react/invariant-failed-router-outside`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

React Router 组件（例如 Link、NavLink、useNavigate）在 Router 上下文提供程序外部使用，通常是由于组件树中缺少或顺序错误的 Router 包装器。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React Router v5.x | active | — | — |
| React Router v6.x | active | — | — |
| React 16.8+ | active | — | — |
| React 18.x | active | — | — |

## 解决方案

1. ```
   在顶层用 Router（例如 BrowserRouter）包裹你的应用或相关组件树。示例：import { BrowserRouter } from 'react-router-dom'; function App() { return (<BrowserRouter><YourRoutes /></BrowserRouter>); }
   ```
2. ```
   如果使用嵌套路由，确保每个路由的组件可以访问路由器上下文；避免在不在 Route 或 Router 内部的组件中渲染 Link。
   ```
3. ```
   对于测试，用 MemoryRouter 或 StaticRouter 包裹组件以提供路由上下文。示例：render(<MemoryRouter><Link to='/'>Home</Link></MemoryRouter>);
   ```

## 无效尝试

- **Importing Router from 'react-router' instead of 'react-router-dom'.** — 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. (70% 失败率)
- **Wrapping only the Link component with a Router, but leaving other parts of the app outside.** — The Router must wrap the entire part of the tree that uses routing; partial wrapping can cause other routing components (like useParams) to fail. (80% 失败率)
- **Using BrowserRouter but forgetting to install 'react-router-dom' and relying on a global script.** — Without proper npm installation, the import may fail or resolve to a different version, leading to context mismatch. (90% 失败率)
