【问题标题】:React Promise: TypeError: Cannot read property 'then' of undefinedReact Promise:TypeError:无法读取未定义的属性“then”
【发布时间】:2018-02-11 08:53:30
【问题描述】:

我需要在我的 API 上发布一些内容。 我有这个可以正常工作的功能:

TradeContainer.js:

callApi(action){
  var actionInfo = {
      user_id: this.props.currentUser.id,
      action: action
  }

  fetch('http://localhost:3000/actions', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(actionInfo)
  })
  .then(res => res.json())
  .then(data => console.log(data))
 }

我想将 fetch() 移动到另一个文件,从该文件中进行所有 API 调用。在那个文件中,我已经有几个获取函数(使用 get 方法)并且它们工作正常。 但是当我将这个带有 post 方法的 fetch() 移动到该文件时,我得到一个错误:

TypeError: 无法读取未定义的属性“then”

我的代码:

TradeContainer.js:

import { saveAction } from '../components/apiCalls.js'

callApi(action){
  var actionInfo = {
      user_id: this.props.currentUser.id,
      action: action
  }

   //this is fetch() function that i moved to apiCalls.js file. 
   //And this two lines of code throw an error.
  saveAction(actionInfo)
  .then(data => console.log(data))
 }

apiCalls.js

export function saveAction(actionInfo){
  fetch('http://localhost:3000/actions', {
   method: 'POST',
   headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/json'
   },
   body: JSON.stringify(actionInfo)
  })
  .then(res => res.json())
}

.then(res => res.json()) 返回“ok”和 200。 但 saveAction(actionInfo) 返回 undefined。怎么会?

【问题讨论】:

  • saveAction 不返回任何内容。
  • 你需要返回调用返回的promise

标签: javascript jquery reactjs promise es6-promise


【解决方案1】:

函数 saveAction 不返回任何内容(特别是 - 不返回承诺),因此您不能在该函数上使用 then

export function saveAction(actionInfo){
  fetch({
     ...
  })
  .then(res => res.json())
}

您可以返回fetch(这是一个承诺),然后您可以在该函数上使用then

export function saveAction(actionInfo){
  return fetch({
     ...
  })
  .then(res => res.json())
}

【讨论】:

  • 我以为事情就是这么简单!非常感谢!
【解决方案2】:

如果对像我这样的菜鸟有任何帮助,请确保returnfetch 语句在同一行,或者将fetch 语句括在括号中。 避免这种情况!它还会导致Cannot read property 'then' of undefined 错误。

function fetchData(){
    return 
       fetch(url)
        .then(response => response.json())
    } 

试试这个。

function fetchData(){
    return (
      fetch(url)
        .then(response => response.json()))
    } 

【讨论】:

猜你喜欢
  • 2018-01-15
  • 1970-01-01
  • 2017-04-21
  • 2021-09-24
  • 1970-01-01
  • 2019-08-19
  • 2016-10-23
  • 2014-09-07
相关资源
最近更新 更多