gpt4 book ai didi

javascript - 通过IPC发送时为"Object has been destroyed"

转载 作者:行者123 更新时间:2023-12-03 12:22:55 25 4
gpt4 key购买 nike

我希望我的 Electron 前端通过 IPC 将用户提供的数据发送到后端,后端处理数据,但也通知前端有关进度,所以我在文档中读到要发送我的东西应该使用 win.webContents.send() 所以我使用了它,但是在使用它的地方抛出 UnhandledPromiseRejectionWarning: E​​rror: Object has been destroyed

let win: BrowserWindow

app.on('ready', () => {
win = new BrowserWindow({ width: 600, height: 400 })

win.loadFile(`/${__dirname}/gui.html`)
})

let sc: Screenshooter

ipcMain.on(
'fire',
async (
event: { sender: { send: (channnel: string, msg: string) => void } },
e: { url: string; args: object; pauseBefore: boolean }
) => {
sc = new Screenshooter(e.url, e.args)
event.sender.send('status', 'preparing')

await sc.prepare().catch(errorExit)

win.webContents.send('status', 'ready') // UnhandledPromiseRejectionWarning: Error: Object has been destroyed

// ...
// more sending contents and operating on object

}
}
)

function errorExit(e: any) {
console.error(e)
dialog.showErrorBox('Error', 'Error: ' + e)
process.exit(1)
}

为什么 win.webContents.send 会抛出错误,我该如何解决?

最佳答案

您在 win.webContents.send 中遇到错误,这会导致 promise 被拒绝并且您的代码不会处理。将代码 package 在 try catch block 中。

// your code

ipcMain.on(
'fire',
async(...Params...) => {
try {
sc = new Screenshooter(e.url, e.args);
event.sender.send('status', 'preparing');
await sc.prepare();
await win.webContents.send('status', 'ready');
} catch(e) {
console.log(e);
}
}
)

错误表明您的 win 对象不再存在,它已被销毁。 win 是对新窗口的引用,看起来你正在关闭窗口(导致 win 对象被破坏),但后来它在 ipcMain 中被引用它找不到 win 对象。

关于javascript - 通过IPC发送时为"Object has been destroyed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55395748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com