求助:Algolia useSortBy出现未处理Promise拒绝问题
问题详情
已经在Algolia创建了items_search_replica副本索引,给它添加了price_asc和price_desc两个排序属性,定义的排序选项代码如下:
const sortByItems = [ { value: "items_search", label: "Relevant" }, { value: "items_search_replica_price_asc", label: "Price (asc)" }, { value: "items_search_replica_price_desc", label: "Price (dsec)" }, ];
同时编写了自定义的CustomSortBy组件:
import { useSortBy } from "react-instantsearch-core"; import { Text, View } from "react-native"; import RadioButtonGroup, { RadioButtonItem } from "expo-radio-button"; const CustomSortBy = (props) => { const { currentRefinement, options, refine: refineSortBy, } = useSortBy({ items: props.items }); return ( <View className="border-b border-b-slate-200"> <Text className="labelText font-extrabold text-md dark:text-white my-3"> Sorting </Text> <View className="p-1 rounded-md"> <RadioButtonGroup containerStyle={{ marginBottom: 10 }} selected={currentRefinement} onSelected={(value) => refineSortBy(value)} > {options.map((item, index) => ( <RadioButtonItem key={index} value={item.value} label={<Text style={{ color: "black" }}>{item.label}</Text>} /> ))} </RadioButtonGroup> </View> </View> ); }; export default CustomSortBy;
运行后弹出「Possible unhandled promise rejection (id:0)」错误,明明useSortBy不是异步函数,不知道问题出在哪。
排查与解决方法
核对副本索引的命名和配置
先去Algolia后台确认items_search_replica_price_asc和items_search_replica_price_desc这两个副本索引是否真实存在,有没有拼写错误——比如你标签里写的Price (dsec)是笔误,会不会索引名也写错成price_dsec了?另外要确认这两个副本索引确实绑定了对应的排序规则,且索引数据已同步完成。处理单选按钮组件的异步回调
虽然refineSortBy本身不是异步函数,但expo-radio-button的onSelected回调可能期望返回一个Promise,直接调用refineSortBy无返回值会触发未处理的Promise拒绝。试试把回调包装成异步函数并捕获错误:onSelected={async (value) => { try { refineSortBy(value); } catch (err) { console.error(err); } }}确认组件在InstantSearch上下文内
检查CustomSortBy组件是否被正确包裹在InstantSearch组件中,如果未接入上下文,useSortBy内部逻辑可能会抛出未被捕获的Promise错误。捕获搜索请求的错误
切换索引时useSortBy会触发Algolia的异步搜索请求,若请求失败(比如网络问题、索引不存在),就会出现Promise拒绝。可以在InstantSearch组件中添加onError回调捕获错误:<InstantSearch searchClient={searchClient} indexName="items_search" onError={(err) => console.error("搜索错误:", err)} > {/* 其他组件 */} <CustomSortBy items={sortByItems} /> </InstantSearch>检查依赖版本兼容性
确认react-instantsearch-core、expo-radio-button和React Native的版本是否兼容,版本不匹配也可能导致异步逻辑异常。
内容的提问来源于stack exchange,提问作者Webie

