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

RN 0.72.6中Turbo Modules包返回null及引用错误求助

React Native Android Turbo Module 搭建问题排查

问题概述

使用RN 0.72.6版本,已启用Fabric和Hermes引擎,严格按照官方文档搭建Android Turbo Modules时遇到两个问题:

  • React Native代码调用模块时触发错误:Cannot read property 'add' of null, js engine: hermes,模块实例返回null,无法实现加法功能
  • CalculatorModule.kt和CalculatorPackage.kt文件中存在Unresolved reference: facebook编译错误

相关代码与目录结构

目录结构

RTNCalculator为标准React Native第三方库结构,核心目录包含:

  • android/:Android原生代码目录,包含CalculatorModule.kt、CalculatorPackage.kt和build.gradle
  • js/:JS层接口定义目录,包含NativeCalculator.ts
  • 根目录:package.json配置文件

CalculatorModule.kt

package com.rtncalculator

import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.rtncalculator.NativeCalculatorSpec

class CalculatorModule(reactContext: ReactApplicationContext) : NativeCalculatorSpec(reactContext) {

  override fun getName() = NAME

  override fun add(a: Double, b: Double, promise: Promise) {
    promise.resolve(a + b)
  }

  companion object {
    const val NAME = "RTNCalculator"
  }
}

CalculatorPackage.kt

package com.rtncalculator;

import com.facebook.react.TurboReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.model.ReactModuleInfo
import com.facebook.react.module.model.ReactModuleInfoProvider

class CalculatorPackage : TurboReactPackage() {
 override fun getModule(name: String?, reactContext: ReactApplicationContext): NativeModule? =
   if (name == CalculatorModule.NAME) {
     CalculatorModule(reactContext)
   } else {
     null
   }

 override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
   mapOf(
     CalculatorModule.NAME to ReactModuleInfo(
       CalculatorModule.NAME,
       CalculatorModule.NAME,
       false, // canOverrideExistingModule
       false, // needsEagerInit
       true, // hasConstants
       false, // isCxxModule
       true // isTurboModule
     )
   )
 }
}

android/build.gradle

buildscript {
  ext.safeExtGet = {prop, fallback ->
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
  }
  repositories {
    google()
    gradlePluginPortal()
  }
  dependencies {
    classpath("com.android.tools.build:gradle:7.3.1")
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.22")
  }
}

apply plugin: 'com.android.library'
apply plugin: 'com.facebook.react'
apply plugin: 'org.jetbrains.kotlin.android'

android {
  compileSdkVersion safeExtGet('compileSdkVersion', 33)
  namespace "com.rtncalculator"
}

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.facebook.react:react-native'
}

js/NativeCalculator.ts

import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import {TurboModuleRegistry} from 'react-native';

export interface Spec extends TurboModule {
  add(a: number, b: number): Promise<number>;
}

export default TurboModuleRegistry.get<Spec>('RTNCalculator') as Spec | null;

package.json

{
  "name": "rtn-calculator",
  "version": "0.0.1",
  "description": "Add numbers with Turbo Native Modules",
  "react-native": "js/index",
  "source": "js/index",
  "files": [
    "js",
    "android",
    "ios",
    "rtn-calculator.podspec",
    "!android/build",
    "!ios/build",
    "!**/__tests__",
    "!**/__fixtures__",
    "!**/__mocks__"
  ],
  "keywords": [
    "react-native",
    "ios",
    "android"
  ],
  "repository": "https://github.com/<your_github_handle>/rtn-calculator",
  "author": "<Your Name> <your_email@your_provider.com> (https://github.com/<your_github_handle>)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/<your_github_handle>/rtn-calculator/issues"
  },
  "homepage": "https://github.com/<your_github_handle>/rtn-calculator#readme",
  "devDependencies": {},
  "peerDependencies": {
    "react": "*",
    "react-native": "*"
  },
  "codegenConfig": {
    "name": "RTNCalculatorSpec",
    "type": "modules",
    "jsSrcsDir": "js",
    "android": {
      "javaPackageName": "com.rtncalculator"
    }
  }
}

解决方案

1. 解决Unresolved reference: facebook编译错误

原因

依赖配置未正确关联宿主项目的React Native版本,或Codegen未生成NativeCalculatorSpec等必要代码。

修复步骤

  • 执行依赖安装与Codegen生成:
    npm install
    npx react-native codegen
    
  • 修改android/build.gradle的依赖配置,使用宿主项目的React Native依赖(避免版本不兼容):
    将dependencies中的implementation 'com.facebook.react:react-native'替换为:
    implementation project(':react-native')
    
    若为远程依赖,需添加RN的Maven仓库并指定对应版本:
    repositories {
      mavenCentral()
      google()
      maven { url 'https://maven.facebook.com' }
    }
    dependencies {
      implementation platform('com.facebook.react:react-native:0.72.6')
      implementation 'com.facebook.react:react-native'
    }
    

2. 解决模块返回null的问题

原因

Turbo Module未在宿主应用中正确注册,或新架构启用不完整。

修复步骤

  • 在宿主项目的MainApplication.kt中注册CalculatorPackage:
    import com.rtncalculator.CalculatorPackage
    
    override fun getPackages(): List<ReactPackage> {
      return PackageList(this).packages.apply {
        add(CalculatorPackage())
      }
    }
    
  • 确认宿主项目已启用新架构:检查gradle.properties中是否存在newArchEnabled=true,若有则执行清理重建:
    cd android
    ./gradlew clean
    ./gradlew assembleDebug
    
  • 验证模块名称一致性:确保NativeCalculator.ts中TurboModuleRegistry.get的名称RTNCalculator与CalculatorModule.NAME完全一致(代码中已匹配,需确认无拼写错误)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:58:13