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

使用getStaticPaths从Sanity取数据时遇Next.js 'client未定义'错误

解决ReferenceError: "client" is not defined错误

问题原因

你的代码中调用了client.fetch(),但没有创建或导入Sanity的客户端实例,导致JS无法识别client变量。

修复步骤

1. 安装Sanity客户端依赖

如果还没安装,先在项目根目录执行命令:

npm install @sanity/client
# 或者用yarn
yarn add @sanity/client

2. 创建并导出Sanity客户端实例

推荐在项目中单独创建一个工具文件(比如lib/sanity.js)来统一管理客户端,避免重复代码:

// lib/sanity.js
import { createClient } from '@sanity/client'

export const client = createClient({
  projectId: '你的Sanity项目ID', // 从Sanity管理后台获取
  dataset: 'production', // 你的数据集名称,默认是production
  apiVersion: '2024-01-01', // 使用最新的API版本,格式为YYYY-MM-DD
  useCdn: true, // 静态生成场景下开启CDN加速,需要实时数据则设为false
})

3. 在ProductPage中导入客户端

在你的页面文件顶部添加导入语句:

import React, { useState } from "react";
import { client } from '../lib/sanity'; // 注意路径要和你的文件结构匹配

4. 优化查询(可选但推荐)

你当前的查询用了字符串拼接'${slug}',存在注入风险,改成参数化查询更安全:

// getStaticProps中的查询修改为
const query = `*[_type == "product" && slug.current == $slug][0]`;
const product = await client.fetch(query, { slug }); // 第二个参数传变量

额外排查点

如果替换教程代码仍报错,检查:

  • Sanity项目ID和数据集名称是否正确,可在Sanity管理后台的「Settings」→「API」中查看
  • 客户端实例的apiVersion是否为有效格式(必须是YYYY-MM-DD)
  • 文件路径是否正确,确保导入client时路径没有写错

内容的提问来源于stack exchange,提问作者Htet Ah Yan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:15:33