# 如何修复 AI 编码代理使用过时的 Next.js API

> AI 代理经常生成使用已弃用的 Pages Router 模式、getServerSideProps 和已在 App Router 项目中删除的 API 的 Next.js 代码。

**Type:** Failure  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, TypeScript  
**Updated:** 2026-06-08

---

AI 代理基于较旧的 Next.js 数据训练，经常在 App Router 项目中生成 `getServerSideProps`、
`getStaticProps` 和 `next/router` 导入，而这些 API 在该项目中并不存在。

## 症状

代理在 `app/` 目录内使用 Pages Router 约定构建页面，导致构建错误或静默无操作。

```tsx
// app/dashboard/page.tsx — WRONG
export async function getServerSideProps() {
  const data = await fetchData();
  return { props: { data } };
}

export default function Dashboard({ data }) {
  return <div>{data.title}</div>;
}
```

在 App Router 中，`getServerSideProps` 导出会被静默忽略；页面渲染时没有数据且没有错误。

## 原因

模型在大量 Next.js 语料库上训练，这些语料库严重偏向于 13 之前的 Pages Router 模式。App Router 在 Next.js 13 中引入（在 14 中稳定），而许多模型的训练截止日期早于广泛应用。代理混淆了这两种范式，因为两者都位于名为 `page.tsx` 的文件中。

## 如何发现

- 在 `app/` 目录下从 `"next/router"` 导入而非 `"next/navigation"`。
- 从 `app/` 下的文件导出 `getServerSideProps`、`getStaticProps` 或 `getStaticPaths`。
- 在文件顶部未添加 `"use client"` 的情况下调用 `useRouter`。
- `next.config.js` 仍使用 `experimental.appDir`（在 Next.js 14 中已删除）。

## 如何修复

用异步 Server Components 替换数据获取导出，并在客户端使用 `next/navigation` 钩子。

```tsx
// app/dashboard/page.tsx — CORRECT
async function fetchData() {
  const res = await fetch("https://api.example.com/data", {
    next: { revalidate: 60 },
  });
  return res.json();
}

export default async function Dashboard() {
  const data = await fetchData();
  return <div>{data.title}</div>;
}
```

检查清单：

```txt
[ ] No getServerSideProps / getStaticProps inside app/
[ ] Use "next/navigation" (useRouter, usePathname, useSearchParams) not "next/router"
[ ] Data fetching is async in the Server Component, not in a prop export
[ ] next.config.js uses next.config.mjs and removes experimental.appDir
[ ] Client-only hooks (useRouter etc.) are inside "use client" components
```

## 修复提示

```txt title="Fix Prompt"
This file uses Pages Router APIs (getServerSideProps, getStaticProps,
next/router) inside an App Router project. Rewrite it using App Router
conventions: async Server Components for data fetching, next/navigation for
routing hooks, and "use client" only where browser APIs are required.
Do not add any Pages Router exports.
```

## 测试

```bash
# Fail fast: no Pages Router exports should appear under app/
grep -rn "getServerSideProps\|getStaticProps\|getStaticPaths" app/ && echo "FAIL: Pages Router API found" || echo "OK"

# Confirm correct navigation import
grep -rn "from \"next/router\"" app/ && echo "FAIL: use next/navigation instead" || echo "OK"
```