BlitzJS查询使用异常:DYNAMIC_SERVER_USAGE错误求助
BlitzJS关联过滤查询出现DYNAMIC_SERVER_USAGE错误的解决
问题场景
在BlitzJS框架中通过关联关系过滤查询表数据时,调用查询函数触发DYNAMIC_SERVER_USAGE错误,无法正常获取数据。
查询函数代码
// 查询函数 import { Ctx, NotFoundError } from "blitz" import { resolver } from "@blitzjs/rpc" import { z } from "zod" import db from "db" const GetProfile = z.object({ id: z.number().optional().refine(Boolean, "Required"), }) export default resolver.pipe( resolver.zod(GetProfile), resolver.authorize(), async ({ id }, ctx: Ctx) => { // TODO: 多租户应用中需添加验证确保租户正确 const profile = await db.annonceur.findFirst({ where: { user: { id: { equals: Number(ctx.session.userId), }, }, }, }) if (!profile) throw new NotFoundError() return profile } )
组件调用代码
import { useMutation, useQuery } from "@blitzjs/rpc" import getProfile from "src/profiles/queries/getProfile" export default function SideBar({ children, active }: Props) { const [profile] = useQuery(getProfile, { }) console.log(profile) return ( // 组件内容省略 ) }
报错信息
[Rendering Suspense fallback...: DYNAMIC_SERVER_USAGE] { digest: 'DYNAMIC_SERVER_USAGE' } - error { name: 'Rendering Suspense fallback...', source: 'server', message: 'DYNAMIC_SERVER_USAGE', digest: 'DYNAMIC_SERVER_USAGE' }
错误原因及解决方案
1. 查询参数与Schema不匹配
查询函数的Zod Schema强制要求id参数,但组件调用useQuery时未传递任何参数,触发验证失败,进而在服务端渲染阶段引发动态内容错误。同时查询逻辑中并未使用id参数,属于冗余定义。
修复方式:
移除Schema中无用的id参数,简化查询函数:
const GetProfile = z.object({}) // 无需参数 export default resolver.pipe( resolver.zod(GetProfile), resolver.authorize(), async (_, ctx: Ctx) => { // 移除未使用的id参数 const profile = await db.annonceur.findFirst({ where: { user: { id: Number(ctx.session.userId), }, }, }) if (!profile) throw new NotFoundError() return profile } )
2. 服务端动态内容处理问题
ctx.session.userId属于服务端动态内容,Next.js(BlitzJS基于Next.js)默认要求服务端渲染内容静态化,因此会触发DYNAMIC_SERVER_USAGE错误。
修复方式:
- 强制查询在客户端执行:给
useQuery添加配置关闭Suspense
const [profile] = useQuery(getProfile, {}, { suspense: false })
- 或在页面组件顶部声明允许动态渲染:
export const dynamic = "force-dynamic"
内容的提问来源于stack exchange,提问作者Lys0243
相关产品推荐
相关产品推荐

