1

I'm developing a Kotlin Multiplatform (KMP) project using JetBrains Compose Multiplatform, targeting Android, Desktop, iOS, and WebAssembly (wasmJs).

In composeApp/src/wasmJsMain/kotlin/org/example/learnkenyang/main.kt for the web target, I used the following code:

@OptIn(ExperimentalComposeUiApi::class)
fun main() {
    ComposeViewport(viewportContainerId = "composeApplication") {
       App()
    }
}

However, when I tried to run the Web (wasm) version, I got this runtime error in the browser console:

Uncaught runtime errors: × ERROR

[object WebAssembly.Exception] at handleError (webpack-internal:///../../node_modules/webpack-dev-server/client/overlay.js:252:58) at eval (webpack-internal:///../../node_modules/webpack-dev-server/client/overlay.js:275:7)

1
  • Please don't add your answer to the question. You can answer your own question, but you need to put the answer in an actual answer. That way people can post alternative answers, and people can vote for questions and answers independently. See the tour. So pleas edit your question and move the answer to an actual answer. Commented Apr 15 at 12:31

1 Answer 1

1

This issue happens because non-JVM platforms like wasmJs cannot use type reflection to instantiate ViewModels via the viewModel() function without an explicit initializer.

✅ Fix

Instead of relying on reflection, explicitly create your ViewModel and pass it into your Composable function manually.

✅ Working fix:

fun main {
ComposeViewport(viewportContainerId = "composeApplication") {

    val viewModel: MainViewModel = MainViewModel() // ✅ Create instance manually

    App(viewModel) // ✅ Pass it in

}
}

📚 Source

JetBrains Docs:

https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-viewmodel.html#using-viewmodel-in-common-code:

\>"On non-JVM platforms, objects cannot be instantiated using type reflection. So in common > code you cannot call the viewModel() function without parameters."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.