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

Electron启动报错:TypeError: Cannot read properties of undefined (reading 'whenReady')

问题分析与修复方案

报错TypeError: Cannot read properties of undefined (reading 'whenReady')的核心原因是错误使用异步import()语法,而非chapter3.mjs的导入问题。你直接对import('electron')的返回值(Promise对象)进行解构,导致app变量为undefined,调用app.whenReady()自然触发报错。path的导入也存在同样问题。

具体修复步骤:

  • 将electron和node:path的异步导入改为静态ES模块导入,因为这两个模块需要同步加载并立即使用。
  • 确保chapter3.mjs中正确导出magicEightBall函数(比如使用export function magicEightBall() {...})。

修正后的main.mjs代码:

// Modules to control application life and create native browser window
import { magicEightBall } from './chapter3.mjs';
import { app, BrowserWindow } from 'electron';
import path from 'node:path';

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html');
  
  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();
  magicEightBall();

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

额外检查:

确认chapter3.mjs的导出格式正确,示例如下:

export function magicEightBall() {
  // 你的函数逻辑
  console.log('magicEightBall 执行');
}

执行npm start后,Electron应用将正常启动,同时magicEightBall函数也会被执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:39:59