React Native:GooglePlacesAutocomplete onPress报错undefined is not a function
undefined is not a function报错 问题诊断
报错undefined is not a function触发位置为HomeScreen.js的GooglePlacesAutocomplete组件onPress回调,结合代码和错误栈,核心原因集中在以下几点:
React导入方式错误
代码中使用import { React } from 'react';的写法不符合React规范,会导致React对象未正确加载,引发JSX编译或回调执行异常。Redux Action Creator异常
如果../slices/navSlice中setOrigin/setDestination未被正确定义为Redux action creator,或者未正确导出,调用dispatch(setOrigin(...))时会因setOrigin是undefined而触发函数调用报错。空值访问引发的连锁问题
虽然设置了details = null的默认值,但当API返回无详细信息的结果时,直接访问details.geometry.location可能触发空值错误,间接导致回调内函数执行异常。Redux Provider未正确包裹组件
若HomeScreen未被Redux的Provider组件包裹,useDispatch会返回undefined,调用dispatch时就会报undefined is not a function。
解决方案
1. 修正React导入
将错误的导入语句:
import { React } from 'react';
改为标准默认导入:
import React from 'react';
2. 验证并修复Redux Action Creator
检查../slices/navSlice文件,确保action creator正确定义并导出:
// navSlice.js示例代码 import { createSlice } from '@reduxjs/toolkit'; const navSlice = createSlice({ name: 'nav', initialState: { origin: null, destination: null, }, reducers: { setOrigin: (state, action) => { state.origin = action.payload; }, setDestination: (state, action) => { state.destination = action.payload; }, }, }); // 必须正确导出action export const { setOrigin, setDestination } = navSlice.actions; export default navSlice.reducer;
3. 添加空值判断避免异常
在onPress回调中先校验details是否存在,再执行后续逻辑:
onPress={(data, details = null) => { // 无详细信息时直接返回,避免报错 if (!details?.geometry?.location) return; dispatch(setOrigin({ location: details.geometry.location, description: data.description, })); dispatch(setDestination(null)); }}
4. 确认Redux Provider配置
确保项目根组件已被Provider包裹,例如:
// App.js示例代码 import { Provider } from 'react-redux'; import store from './store'; import HomeScreen from './screens/HomeScreen'; export default function App() { return ( <Provider store={store}> <HomeScreen /> </Provider> ); }
验证步骤
- 重启React Native开发服务器
- 重新构建项目,测试
GooglePlacesAutocomplete的选择功能,确认报错消失
内容的提问来源于stack exchange,提问作者Dan Carlton

