首次在React.js中用Cloud Functions实现FCM推送遇非空对象错误
解决FCM推送「Message must be a non-null object」错误
错误原因
你调用了错误的FCM发送方法。admin.messaging().send()用于发送单条推送消息,它的参数是一个包含推送目标(如token/topic)和内容的消息对象,而非直接传入tokens数组和payload。你现在把tokens作为第一个参数传入,导致方法接收到的「消息对象」是一个数组(不符合预期的消息结构),从而触发「Message must be a non-null object」错误。
解决方案
改用批量发送方法,推荐使用sendMulticast()(Firebase Admin SDK v10+支持),也可以用旧版的sendToDevice(),以下是两种方案的代码修正:
方案1:使用sendMulticast()(推荐)
替换原代码中发送通知的逻辑:
if (tokens.length > 0) { // 构造批量推送消息,将tokens放入消息对象的tokens字段 const message = { notification: payload.notification, tokens: tokens }; const response = await admin.messaging().sendMulticast(message); await cleanupTokens(response, tokens); functions.logger.log('Notifications have been sent and tokens cleaned up.'); }
方案2:使用sendToDevice()(旧版API)
如果你的SDK版本较低,也可以用这个专门针对设备token批量推送的方法:
if (tokens.length > 0) { // sendToDevice直接接收tokens数组和payload const response = await admin.messaging().sendToDevice(tokens, payload); await cleanupTokens(response, tokens); functions.logger.log('Notifications have been sent and tokens cleaned up.'); }
额外优化建议
为避免payload出现空值导致的潜在问题,可对username字段做兜底处理:
const username = snapshot.data().username || 'Someone'; const payload = { notification: { title: `${username} sent ${text ? 'a new message' : 'a new attachment'}`, body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '', icon: snapshot.data().photoURL || '/images/profile_placeholder.png', } };
内容的提问来源于stack exchange,提问作者Kareem Abbas
相关产品推荐
相关产品推荐

