调用Yelp API反复触发Possible Unhandled Promise Rejection警告求助
解决Yelp API调用中的"Possible Unhandled Promise Rejection"警告
出现这个警告,核心原因是代码里的Promise错误未被正确捕获,再加上API地址、状态处理的几个问题,具体修复方案如下:
问题排查与修复点
- API端点错误:你用的是Yelp的文档页面URL,不是实际的API接口地址,这会导致请求返回HTML而非JSON,解析时直接触发错误。正确的商家搜索接口是
https://api.yelp.com/v3/businesses/search。 - Promise错误未捕获:
- 原代码的
try/catch无法覆盖fetchPromise链中的错误(比如网络失败、JSON解析失败),需要改用async/await配合try/catch,或者在then链末尾添加.catch()。 useEffect中调用getResturantFromYelp()返回的Promise没有处理rejection,需要确保所有异步错误都被捕获。
- 原代码的
- 状态处理错误:你把
json.businesses转成字符串存在state里,后续渲染时resturant_Data.map()会报错(字符串没有map方法),应该直接存储数组对象。
修复后的代码
API调用代码
const [resturantData, setResturantData] = React.useState(localResturant); const getResturantFromYelp = async () => { // 修正为正确的API端点 const yelpurl = 'https://api.yelp.com/v3/businesses/search?term=restaurants&location=SanDiego'; const apiOptions = { headers: { Authorization: `Bearer ${YELP_API_KEY}`, }, }; try { const res = await fetch(yelpurl, apiOptions); // 检查HTTP响应是否成功(比如401、404这类错误fetch不会自动reject) if (!res.ok) { throw new Error(`请求失败,状态码:${res.status}`); } const json = await res.json(); // 直接存储数组,无需转成字符串;如果接口返回空数据,设为默认空数组 setResturantData(json.businesses || []); } catch (error) { console.error('获取餐厅数据失败:', error); // 出错时回退到本地默认数据 setResturantData(localResturant); } }; useEffect(() => { getResturantFromYelp(); }, []);
渲染代码(增加数组校验)
export default function ResturantItems({resturant_Data}) { // 先校验是否为数组,避免map报错 if (!Array.isArray(resturant_Data)) { return <View style={{padding: 15}}>暂无餐厅数据</View>; } return ( <TouchableOpacity activeOpacity={1} style={{marginBottom:15}}> {resturant_Data.map((resturant, index) => ( <View key={index} style={{ backgroundColor: '#fff', padding: 7, marginTop: 7 }}> <ResturantImage image={resturant.image_url} /> <ResturantInfo name={resturant.name} rating={resturant.rating} /> </View> ))} </TouchableOpacity> ); }
内容的提问来源于stack exchange,提问作者Zeeshan Aslam
相关产品推荐
相关产品推荐

