React Native中Kotlin调用JS函数报错:myFun is not defined
Hey there! Let's work through this interop issue you're facing—it's super common when setting up Kotlin/JS with React Native, so let's break down the likely causes and fixes:
1. Ensure Your JS Function is Accessible to Kotlin
Kotlin's external functions look for the target function in the global scope by default. If you're only exporting myFun from your App.js module without exposing it globally, Kotlin won't be able to find it.
In your App.js, add this line after defining/exporting myFun to attach it to React Native's global object:
export function myFun() { console.log("Hello from JS!"); } // Expose to global scope so Kotlin can resolve it global.myFun = myFun;
2. Use @JsModule to Link Kotlin to Your JS Module
If you don't want to pollute the global scope, you can tell Kotlin exactly which JS module to pull myFun from using the @JsModule annotation. Adjust the path to match your project's directory structure (make sure it points correctly to App.js):
// Main.kt import kotlin.js.JsModule @JsModule("./App") // Update the path if your App.js is in a different location external fun myFun()
Note: If you're using Kotlin/JS's IR compiler, double-check your build.gradle.kts for correct module system configuration (should be set to commonjs to match your shared module).
3. Verify Load Order: JS Must Initialize Before Kotlin Calls
It's possible your Kotlin code is trying to call myFun before your App.js has loaded and exported the function.
In React Native, make sure your index.js (or entry file) loads App.js first before initializing your Kotlin shared module. Alternatively, wrap your Kotlin call in a React lifecycle method (like useEffect for functional components or componentDidMount for class components) to ensure JS has fully initialized:
// In App.js import { useEffect } from 'react'; import { myKotlinFunctionThatCallsMyFun } from './shared'; // Import your Kotlin function function App() { useEffect(() => { // Call Kotlin only after the component mounts (JS is ready) myKotlinFunctionThatCallsMyFun(); }, []); // ... rest of your component }
4. Use @JsName to Avoid Name Mangling
Sometimes JS bundlers (like Metro in React Native) or minifiers can rename functions during compilation. Use @JsName in Kotlin to explicitly specify the exact function name it should look for:
// Main.kt import kotlin.js.JsName @JsName("myFun") external fun myFun()
This ensures Kotlin doesn't get confused if your bundler modifies the function's name behind the scenes.
Quick Troubleshooting Checklist
- Double-check your
sharedmodule's build configuration is set to outputcommonjs - Confirm the path in
@JsModuleis relative to your Kotlin source file's location - Test by calling
myFun()directly from the JS console first to ensure it works
内容的提问来源于stack exchange,提问作者Warlock

