无法在 React 应用程序中中止超级代理

Cannot abort superagent in React app

我正在重构我构建的 React 应用程序中的一些代码,以便使用 superagent instead of jQuery 向 Tumblr api 发出 ajax 请求。

注意当使用coffeescript时@等同于'this'.

我的 jQuery ajax 对 tumblr api 的调用如下:

App = React.createClass

  loadPhotos: ->

    data =
      api_key: 'xxx'

    blog = 'tumblrname'
    url = "http://api.tumblr.com/v2/blog/#{blog}.tumblr.com/posts/photo"


    @xhr = $.ajax
      url: url
      type: 'GET'
      dataType: 'jsonp'
      data: data
      success: (data) =>   

        console.log @xhr, @         

控制台输出为:

Object {readyState: 4, responseJSON: Object, status: 200, statusText: "load"} Constructor {props: Object, context: Object, refs: Object, updater: Object, state: Object…}

当我使用 jQuery 时一切正常,我可以调用 @xhr.abort() 来中止 ajax 调用。

然而,当我切换到使用 superagent 时,调用成功,我可以访问响应数据,但是我无法访问 @xhr 变量来中止请求。

我的超级代理 ajax 电话:

superagent = require 'superagent'
jsonp = require 'superagent-jsonp'

App = React.createClass

  loadPhotos: ->

    data =
      api_key: 'xxx'

    blog = 'tumblrname'
    url = "http://api.tumblr.com/v2/blog/#{blog}.tumblr.com/posts/photo"


    @xhr = superagent
      .get url 
      .use jsonp
      .query data 
      .end (err, res) =>

        console.log @xhr, @ 

此代码的控制台输出为:

undefined Constructor {props: Object, context: Object, refs: Object, updater: Object, state: Object…}

如果我将 superagent .end 更改为使用 -> 而不是 => console.log(this) returns:

Request {_query: Array[2], method: "GET", url: "http://api.tumblr.com/v2/tagged", header: Object, _header: Object…}

我需要调用 .abort() 来中止 ajax 调用。不幸的是,我需要使用粗箭头才能在对响应数据执行操作时使用 this.state。

我的问题是:当我使用 superagent 而不是 jQuery 时,为什么 @xhr 返回 undefined,以及如何更新我的代码以允许访问 @xhr,以便我可以在其上调用 .abort()根据需要?

正如@azium 提到的,我解决这个问题的方法是使用 self = this,然后在 superagent .end() 函数中设置 @xhr。我还将数据操作重构为另一个函数 processResponse()。工作代码如下:

superagent = require 'superagent'
jsonp = require 'superagent-jsonp'

App = React.createClass

  loadPhotos: ->

    self = @ 

    data =
      api_key: 'xxx'

    blog = 'tumblrname'
    url = "http://api.tumblr.com/v2/blog/#{blog}.tumblr.com/posts/photo"

    req = superagent
      .get url 
      .use jsonp
      .query data 
      .end (err, res) ->

        self.xhr = @

        self.processResponse(res.body)

  processResponse: (data) ->
    # do the stuff to the response data with @state