Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jaypee(PH)'s avatar

Variable inside the child component gets undefined?

Hell guys. im using vuejs with axios and i got this line of code that will fetch a list of records (students) in my database and its working but the problem is when i try to put the response on a variable. i end up getting this error. "Uncaught (in promise) TypeError: Cannot set property 'students' of undefined"

by the way here is my code in vue.

<script>
    export default {
        data(){
            return{
                students: {},
                    title: 'Student List',  
                }
            },
        beforeMount(){
            this.loadstudent();
        },
        methods:{
            loadstudent(){
                axios.get('/information').then(function(response){
                    console.log(response.data)
                    this.students = response.data;
                    
                });
            }
        }

        
    }
</script>

tried to put the code inside a method loadstudent. assuming that the mounted is the reason behind. but still got nothing. hope some could help me. thank you in advance.

0 likes
2 replies
bunnypro's avatar
bunnypro
Best Answer
Level 7

the problem is in your loadstudents method. you can't call this directly inside closure.

the solution is to use es6 arrow syntax or bind the this

axios.get( ... ).then(response => {
    ...
})

or

axios.get( ... ).then(function (response) {
    ...
}.bind(this))

Please or to participate in this conversation.