使用whatsapp-web.js发消息报错:Cannot read properties of undefined (reading 'serialize')
问题:使用whatsapp-web.js批量发送消息时出现"Cannot read properties of undefined (reading 'serialize')"报错
报错信息
throw new Error('Evaluation failed: ' + helper_js_1.helper.getExceptionMessage(exceptionDetails));
^Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'serialize')
我的代码
const Client = require('whatsapp-web.js').Client; const qrcode = require('qrcode-terminal'); const client = new Client(); client.on('qr', (qr) => { console.log('Scan the following QR Code:'); qrcode.generate(qr, {small: true}); }); client.on('ready', async () => { console.log('Client is ready!'); }); client.on('message_create', async msg => { if (!msg.fromMe) return; if (msg.body.startsWith('-love')) { console.log('Sending love messages ' + msg.to.replace('@g.us', '')) var chat = await msg.getChat() var args = msg.body.split(' ').slice(1) var sentMessage = 'I love you <3' var amount = Math.floor(args[0]) || 10 for (let i = 0 ; i < amount ; i++) { chat.sendMessage(sentMessage) console.log('Sended Message') } } }) client.initialize();
已尝试的解决方法
- 修改whatsapp-web.js目录下的Injected.js文件
- 断开其他登录设备
- 使用chat-id发送消息
环境信息
- Node版本:19.0.0
- Windows版本:21H2
预期效果
执行-love命令后,向好友发送指定数量的“I love you <3”消息
解决方法
这个报错多由异步操作未正确处理、版本兼容性或对象异常导致,以下是可行修复方案:
- 给消息发送添加异步等待
原循环里直接调用chat.sendMessage但未等待异步操作完成,会打乱WhatsApp Web的上下文,引发序列化错误。修改循环部分:
for (let i = 0 ; i < amount ; i++) { await chat.sendMessage(sentMessage) console.log('已发送第' + (i+1) + '条消息') }
降级Node版本
Node 19属于非LTS版本,和whatsapp-web.js存在兼容性问题,建议降级到16.x或18.x这类稳定LTS版本,多数用户反馈降级后该错误会消失。清理缓存并重装依赖
- 删除项目下的
session.json文件(如果存在) - 卸载并重新安装依赖:
npm uninstall whatsapp-web.js qrcode-terminal npm install whatsapp-web.js qrcode-terminal - 重新运行脚本并扫码登录
- 校验chat对象有效性
获取chat后增加判断,避免操作异常对象:
var chat = await msg.getChat() if (!chat) { console.log('无法获取聊天对象') return }
内容的提问来源于stack exchange,提问作者Coffee
相关产品推荐
相关产品推荐

