我希望我的电子前端将用户提供的数据通过IPC发送到后端,并由后端处理数据,但也要通知前端进度,所以我在文档中读到要发送内容应该使用win.webContents.send(),所以我使用了它,但在使用它的地方抛出了UnhandledPromiseRejectionWarning: Error: 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会抛出错误,我该如何修复呢?
发布于 2019-03-28 20:02:44
您在win.webContents.send中遇到错误,这将导致您的代码无法处理promise rejection。将代码包装在try catch块中。
// 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对象。
https://stackoverflow.com/questions/55395748
复制相似问题