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

Sanity报错:Uncaught TypeError: fetch不是一个函数

解决Uncaught TypeError: sanityClient.fetch is not a function错误

错误原因

你遇到的问题是**@sanity/client v3及以上版本不再默认导出已初始化的客户端实例**,你当前直接导入的sanityClient其实是创建客户端的方法,并非可直接调用fetch的实例,因此触发“fetch不是函数”的报错。

修复步骤

  1. 正确初始化Sanity客户端
    替换原有导入语句,调用createClient方法创建配置好的客户端实例,需填入你的Sanity项目ID、数据集名称和API版本(API版本建议使用当前年份月份,比如2024-05-01)。

  2. 修正JSX语法错误
    你的img标签存在两处问题:

    • src属性的表达式写法错误,需用模板字符串${}而非引号包裹{}
    • React中img标签需自闭合,即写成<img ... />

修正后的完整代码

import React, { useState, useEffect }from 'react';
import './about.css'
import { createClient } from "@sanity/client";

// 初始化Sanity客户端
const sanityClient = createClient({
  projectId: "你的项目ID", // 替换为你的Sanity项目ID
  dataset: "你的数据集名称", // 替换为你的数据集名称(如"production")
  apiVersion: "2024-05-01", // 使用最新API版本
  useCdn: true, // 可选:开启CDN加速,根据需求调整
});

export default function About() {

    const [aboutData, setAbout] = useState(null);

    useEffect(() => {
        sanityClient
            .fetch(`*[_type=="website_images"]{
                alt,
                about{
                    asset->{
                        _id,
                        url
                    }
                }
            }`)
            .then((data) => setAbout(data))
            .catch(console.error);
    }, [] );

    return (
        <main className="main-about">
            <div className="about-body">
                <div className="about-title">
                    <div className="title-line-left"></div>
                    <h2>about</h2>
                    <div className="title-line-right"></div>
                </div>
                <div className="about-text">
                    <p className="pronouns">(they/them)</p>
                    <p>The Japanese city and the Prefecture of Hiroshima may have been devastated by the atomic bomb over 76 years ago, but today, this site of the destruction is one of the top tourist destinations in the entire country. Statistics released by the nation's tourist agency revealed that around 363,000 visitors went to the metropolis during 2012, with Americans making up the vast majority of that figure, followed by Australians and Chinese.</p>
                </div>
            </div>
            {aboutData && aboutData.map((website_images, index) => (
            <figure className="photo-position" key={index}>
                    <img src={website_images.about.asset.url} alt={website_images.alt} className="about-photo" />
            </figure>
            ))}
        </main>
    )
}

额外提示

  • 项目ID和数据集名称可在Sanity Studio管理界面中找到
  • 若仍使用@sanity/client v2版本,需检查安装是否正确(v2默认导出实例,但建议升级至v3以使用最新特性)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:03:44