React Native Mobx中如何将bookmarkapi返回数组赋值给petList并解决报错
报错原因
then回调中使用普通函数声明导致this指向偏移:普通函数的this会绑定到调用时的执行上下文,此处Promise回调的执行上下文不是你的Mobx store实例,因此访问this.userId时返回undefined,触发类型错误。同时你没有为异步请求添加错误捕获,才会抛出「Unhandled promise rejection」提示。
修复方案
两种修改方式二选一即可:
方案1:替换为箭头函数回调
箭头函数不绑定独立的this,会继承外层作用域的this(即store实例),同时补充错误捕获逻辑:
bookMarkList = async () => { const value = await AsyncStorage.getItem('userId') if (value != null) { this.userId = value; console.log(this.userId); } bookmarkApi.get('/') .then((responseJson) => { // 改为箭头函数修正this指向 this.petList = responseJson.data.filter(data => data.userId == this.userId) }) .catch(err => { // 补充错误捕获避免未处理的rejection报错 console.log('获取书签列表失败', err) }) }
方案2:统一使用async/await写法(更推荐)
完全替换回调写法,逻辑更清晰,也不会出现this指向问题:
bookMarkList = async () => { try { const value = await AsyncStorage.getItem('userId') if (value != null) { this.userId = value; console.log(this.userId); } const responseJson = await bookmarkApi.get('/') this.petList = responseJson.data.filter(data => data.userId == this.userId) } catch (err) { console.log('操作失败', err) } }
额外注意点
AsyncStorage取出的userId是字符串类型,如果后端返回的data.userId是数字类型,建议统一类型后再比较,避免匹配失败:
// 示例:将取出的userId转成数字 this.userId = Number(value);
内容的提问来源于stack exchange,提问作者yasin
相关产品推荐
相关产品推荐

