docs/developer/electron-ipc-best-practices.md
在Electron应用中,Vue的响应式对象不能直接通过IPC(进程间通信)传递,会导致"An object could not be cloned"错误。这是因为Vue的响应式对象包含了不可序列化的代理包装器。
✅ 现在的做法:
// 可以直接传递Vue响应式对象,ElectronProxy会自动序列化
await modelManager.addModel(newModel.value.key, {
name: newModel.value.name,
llmParams: newModel.value.llmParams // ElectronProxy会自动清理响应式包装
})
架构优势:
ElectronProxy层自动处理序列化:
技术实现:
packages/core/src/utils/ipc-serialization.ts 中的 safeSerializeForIPC 函数当你看到以下错误时,说明存在IPC序列化问题:
An object could not be clonedDataCloneErrorFailed to execute 'postMessage'// ✅ 现在可以直接传递Vue响应式对象
await modelManager.addModel(key, {
llmParams: formData.value.llmParams // ElectronProxy会自动序列化
})
// ✅ 现在可以直接传递Vue响应式对象
await historyManager.createNewChain({
metadata: { mode: optimizationMode.value } // ElectronProxy会自动序列化
})
// ✅ 现在可以直接传递Vue响应式对象
await templateManager.saveTemplate({
content: form.value.messages // ElectronProxy会自动序列化
})
现在开发更简单了,只需要检查:
console.log('Object type:', Object.prototype.toString.call(obj))
console.log('Is reactive:', obj.__v_isReactive)
console.log('Is ref:', obj.__v_isRef)
try {
JSON.stringify(obj)
console.log('Object is serializable')
} catch (error) {
console.error('Object is not serializable:', error)
}
在Chrome DevTools中,响应式对象会显示为 Proxy 类型。
序列化处理已经移到ElectronProxy层,Vue组件可以直接调用:
// 在组件方法中 - 现在更简单了
const handleSave = async () => {
await service.save(formData.value) // 直接传递,无需手动序列化
}
当添加新的ElectronProxy方法时,对复杂对象参数进行序列化:
async newMethod(complexObject: SomeType): Promise<ResultType> {
// 对复杂对象参数进行序列化
const safeObject = safeSerializeForIPC(complexObject);
return this.electronAPI.someService.newMethod(safeObject);
}
ElectronProxy的接口应该接受Vue响应式对象,内部自动处理:
interface IModelManager {
addModel(key: string, config: ModelConfig | Ref<ModelConfig>): Promise<void>
// 接口层面支持响应式对象,实现层面自动序列化
}
JSON.parse(JSON.stringify()) 确保100%兼容性现在的架构已经大大简化了Electron IPC的使用:
记住:现在可以放心地传递Vue响应式对象,架构会自动处理!