You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将代码移入src目录后tRPC失效:TypeError问题求助

问题:Next.js + tRPC项目移入src目录后触发TypeError: Cannot read properties of null (reading 'client')

我正在用Next.js和tRPC开发一个简易推特克隆项目,原本tRPC功能完全正常,但在将所有代码移入src目录、修正完所有导入路径后,tRPC突然停止工作,抛出错误:

TypeError: Cannot read properties of null (reading 'client')

错误触发点位于src/pages/index.tsx的第7行查询代码处。

原本的项目根目录结构

.
├── components
├── containers
├── model
├── next.config.js
├── next-env.d.ts
├── package.json
├── pages
├── postcss.config.js
├── prettier.config.js
├── prisma
├── README.md
├── routers
├── tailwind.config.js
├── tsconfig.json
├── utils
└── yarn.lock

7 directories, 9 files

此前的正常配置步骤

我之前严格按照tRPC的Next.js配置指南完成了以下设置:

  • 创建tRPC路由:在routers/TweetRouter.ts定义路由,并在pages/api/trpc/[trpc].ts中合并
  • 创建tRPC钩子:在utils/trpc.ts中实现
  • 配置_app.tsx:引入QueryClientProvider及withTRPC
  • 发起API请求:在首页组件中使用trpc.useQuery获取数据,原本可正常运行

调整后的项目目录结构

src
├── backend
│   ├── model
│   │   ├── tweet.ts
│   │   └── user.ts
│   └── router
│       ├── index.ts
│       └── tweet.ts
├── components
│   ├── LikesCounter.tsx
│   └── TweetCard.tsx
├── containers
│   └── Page.tsx
├── pages
│   ├── api
│   │   └── trpc
│   │       └── [trpc].ts
│   ├── _app.tsx
│   └── index.tsx
├── styles
│   └── globals.css
└── utils
    └── trpc.ts

10 directories, 14 files

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:09:26