React Native Alert.alert报错:unrecognized selector sent to instance 求助
Fix for Alert.alert "unrecognized selector sent to instance" Error
嘿,我一眼就揪出问题所在啦!你遇到的这个报错,根源是Alert.alert的参数顺序完全搞错了。
问题原因
React Native里Alert.alert的正确参数结构是:
- 标题字符串(必填)
- 消息文本字符串(可选,可传空字符串或
undefined) - 按钮配置数组(可选)
- 额外配置选项(可选)
你的代码里直接把按钮数组放在了第二个参数的位置,RN内部会把这个数组当成“消息文本”去处理。底层调用OC的方法时,它期望接收一个字符串,结果拿到了数组,就会尝试调用字符串的length方法——但数组根本没有这个方法,自然就抛出了NSArray length; unrecognized selector sent to instance的错误。
修复后的代码
只需要补上第二个参数的位置(哪怕是空字符串也行),就能解决问题:
acceptFriendRequest(friendsName){ Alert.alert( friendsName + ' wants to add you', '', // 补上消息参数,位置不能少 [ {text: 'Decline', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, {text: 'Accept', onPress: () => this.confirmFriendRequest(this), style: 'accept'}, ], ) }
如果有需要展示的消息内容,直接把空字符串换成你的消息文本就好,比如:
Alert.alert( friendsName + ' wants to add you', 'Would you like to accept this friend request?', // 这里填实际消息 [/* 按钮数组 */] )
额外提醒
别小看参数顺序的问题,React Native的原生桥接层对参数类型和位置要求很严格,稍微错位就会触发这类底层报错。以后调用API时,记得多核对官方文档的参数签名哦~
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

