You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Ajax请求返回undefined且提示callback is not defined问题求解

问题原因及修复方案

报错"callback is not defined"的原因

代码中手动指定了jsonpCallback: "callback",但未全局声明名为callback的函数。jQuery发起jsonp请求时默认会自动生成随机回调函数名、自动挂载全局函数并在请求结束后清理,无需手动指定jsonpCallback参数,删掉该行配置即可解决该报错。

返回值为undefined的原因

Ajax请求是异步执行的,getUserGps函数本身没有定义返回值,success回调中的return city仅作用于回调函数内部,不会作为getUserGps的返回值返回给调用方,因此同步调用getUserGps()只能拿到undefined。

完整修复方案

1. 改造getUserGps方法,返回Promise处理异步结果

import $ from 'jquery'
export const getUserGps = () => {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "https://geolocation-db.com/jsonp",
            dataType: "jsonp",
            success: function(location) {
                const city = location.city
                console.log('Pobrano z gps ' + location.city)
                resolve(city)
            },
            error: (err) => reject(err)
        })
    })
}

2. 组件中调用异步方法获取结果

调用方式1:使用.then链式调用

getUserGps().then(city => {
  console.log(city)
  // 此处写拿到城市后的业务逻辑
})

调用方式2:React函数组件中结合async/await使用

import { useEffect, useState } from 'react'

const DemoComponent = () => {
  const [currentCity, setCurrentCity] = useState('')

  useEffect(() => {
    const getCity = async () => {
      try {
        const city = await getUserGps()
        console.log(city)
        setCurrentCity(city)
      } catch (err) {
        console.error('定位获取失败', err)
      }
    }
    getCity()
  }, [])

  return <div>定位城市:{currentCity}</div>
}

内容的提问来源于stack exchange,提问作者Wiktor Maciążek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 17:45:05