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

Sanity.io接入App报错:TypeError与main未注册问题求助

解决React Native接入Sanity时的TypeError及AppRegistry注册错误

问题描述

以下是用于接入Sanity的客户端代码:

import { ImageUrlBuilder } from "@sanity/image-url";
import { createClient } from "@sanity/client";

const client = createClient({
    projectId: 'project_id',
    dataset: 'production',
    useCdn: true,
    apiVersion: '2022-01-12', 
});

const builder = ImageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);

export default client;

运行时出现以下报错:

TypeError: undefined is not a function, js engine: hermes
ERROR Invariant Violation: "main" has not been registered. This can happen if:

  • Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
  • A module failed to load due to an error and AppRegistry.registerComponent wasn't called., js engine: hermes

解决方案

1. 修复模块加载失败的TypeError

该错误大概率是Sanity依赖版本与React Native/Hermes环境不兼容导致:

  • 卸载现有依赖:
    npm uninstall @sanity/client @sanity/image-url
    
  • 安装经过验证的兼容版本:
    npm install @sanity/client@6.0.0 @sanity/image-url@1.0.2
    

2. 修正Sanity客户端配置

代码中的project_id是占位符,必须替换为真实配置:

  • 登录Sanity Studio,在项目设置中复制Project ID,替换代码里的'project_id'
  • 确认dataset名称与你Sanity项目中的数据集完全一致(默认是production,若自定义过需修改)

3. 重置Metro服务器缓存

按报错提示处理Metro问题:

  • 关闭当前运行的Metro服务器(按Ctrl+C终止)
  • 删除Metro缓存:
    rm -rf node_modules/.cache
    
  • 重启Metro并清除缓存:
    npx react-native start --reset-cache
    
  • 重新运行App:
    npx react-native run-android # iOS环境用npx react-native run-ios
    

4. 检查App入口文件的注册逻辑

确保项目入口文件(通常是index.js或App.js)正确调用AppRegistry.registerComponent:

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

若入口文件存在语法错误或依赖导入失败,也会触发该报错,需仔细排查入口代码逻辑。

5. 排查Hermes兼容性(可选)

若上述步骤无效,临时禁用Hermes测试:

  • 打开android/app/build.gradle,修改enableHermes为false:
    project.ext.react = [
      enableHermes: false,
    ]
    
  • 清理Android构建缓存:
    cd android && ./gradlew clean
    
  • 重新运行App,若错误消失,建议更新React Native到最新稳定版解决Hermes兼容性问题。

验证代码

配置正确后,可在组件中测试Sanity数据请求:

import client from './path-to-your-sanity-client-file';

const fetchSanityData = async () => {
  try {
    const data = await client.fetch('*[_type == "your-document-type"]');
    console.log('Sanity数据:', data);
  } catch (error) {
    console.error('请求失败:', error);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:05:27