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

Next.js 14服务器组件渲染错误及@tanstack/react-query错误处理咨询

解决Next.js生产环境Server Components中@tanstack/react-query的错误捕获问题

核心问题分析

生产环境下Next.js会隐藏Server Components的错误详情,而常规的error.tsx(页面/全局级)仅能捕获Client Components或页面路由的错误,无法处理Server Components中@tanstack/react-query触发的异常。

具体解决方案

1. 在Server Components中手动捕获查询错误

Server Components无法使用React Error Boundary,必须在查询逻辑中直接处理错误:

  • 用try/catch包裹查询函数,捕获并处理异常
  • 配置useQuery的onError回调记录或处理错误

示例代码:

// Server Component 示例
import { useQuery } from '@tanstack/react-query'

async function fetchServerData() {
  try {
    const res = await fetch(process.env.NEXT_PUBLIC_API_URL + '/data', {
      cache: 'no-store'
    })
    if (!res.ok) throw new Error(`请求失败: ${res.status}`)
    return res.json()
  } catch (err) {
    // 记录生产环境日志,方便排查
    console.error('服务端查询异常:', err)
    // 抛出用户友好的错误,或返回默认数据
    throw new Error('数据加载失败,请稍后重试')
  }
}

export default function ServerPage() {
  const { data, error } = useQuery({
    queryKey: ['server-data'],
    queryFn: fetchServerData,
    onError: (err) => {
      // 额外的错误处理逻辑,比如上报监控
      console.error('React Query 错误:', err)
    }
  })

  // 直接在Server Component中渲染错误提示
  if (error) {
    return <div className="error">{error.message}</div>
  }

  return <div>{data?.content}</div>
}

2. 配置全局致命错误捕获组件

创建app/global-error.tsx(必须标记为Client Component),捕获包括Server Components在内的全局致命错误:

'use client'

export default function GlobalError({ error, reset }: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  return (
    <html>
      <body className="min-h-screen flex flex-col items-center justify-center p-4">
        <h2 className="text-red-500 text-xl mb-4">系统出错了</h2>
        <p className="mb-6">{error.message}</p>
        <button 
          onClick={() => reset()}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          刷新重试
        </button>
      </body>
    </html>
  )
}

3. 优化React Query服务端配置

在根layout.tsx中调整QueryClient配置,确保生产环境错误能被正确抛出:

// app/layout.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        // 生产环境减少重试次数,避免重复触发错误
        retry: 1,
        // 强制抛出错误,方便上层捕获
        throwOnError: true,
        // 按需调整缓存策略,确保数据有效性
        cacheTime: 300000
      }
    }
  })

  return (
    <html lang="zh-CN">
      <body>
        <QueryClientProvider client={queryClient}>
          {children}
        </QueryClientProvider>
      </body>
    </html>
  )
}

4. 查看生产环境详细错误日志

Next.js生产环境隐藏前端错误详情,需查看服务器端日志:

  • 若使用Vercel/Netlify等托管平台,进入项目日志面板查看Functions或Server Components的错误栈
  • 自建服务器则查看Node.js控制台输出,定位具体错误来源(如API请求失败、参数错误等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:16:04