Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

axios Cannot read property 'cancelToken' of undefined

在vue2.0中使用axios向后台请求数据

全局配置axios, /src/apis/index.js

import axios from 'axios';
import qs from 'qs';

axios.defaults.baseURL = 'http://usergroup.laile.com/api_group/v1/';
axios.defaults.timeout = 5000;

axios.interceptors.request.use((config) => {
  if(config.method === 'post') {
    config.data = qs.stringify(config.data);
  }
}, (error) => {
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  if(!res.data.success) {
    return Promise.reject(res);
  }
  return res;
}, (error) => {
  return Promise.reject(error);
});

export default axios;

/src/apis/mountedUsers.js 某个页面的接口文件

import axios from './index';
export default {
  getCities() {
    return axios.get(`/city/opened-list`);
  }
}

/src/store/modules/mountedUsers.js

import api from '../../apis/mountedUsers'
import * as types from '../types'
const state = {
  cities: []
}
const getters = {
  cities: state => state.cities
}
const actions = {
  getCities({ commit }) {
    api.getCities().then(res => {
      commit(types.GET_CITIES, res.data)
    });
  }
}
const mutations = {
  [types.GET_CITIES](state, cities) {
    state.cities = cities;
  }
}
export default {
  state,
  getters,
  actions,
  mutations
}

入口文件 main.js

import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store/index';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css';    // 默认主题
import '../static/css/pzq.css';  
import "babel-polyfill";
Vue.use(ElementUI);
Vue.config.devtools = true;
new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

当我在页面中发送this.$store.dispatch('getCities')的时候,报Uncaught (in promise) TypeError: Cannot read property 'cancelToken' of undefined,请问是什么原因呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

/src/apis/index.js

axios.interceptors.request.use((config) => {
  if(config.method === 'post') {
    config.data = qs.stringify(config.data);
  }
  return config;  //添加这一行
}, (error) => {
  return Promise.reject(error);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...