VueJS问题:mounted钩子中无法访问已赋值的this.user.id
Hey there! I see exactly what's tripping you up here—let's fix this step by step.
The Core Problem: Asynchronous Code Execution
Axios GET requests are asynchronous, meaning they don't block the rest of your code from running. Right now, you're trying to access this.user.id immediately after starting the request, but the request hasn't finished yet! The then() callback where you assign this.user = response.data runs later, after the API sends back data. So when your this.$echo.channel(...) line runs, this.user is still the empty array you initialized in data(), hence this.user.id is undefined.
Fix 1: Move Echo Initialization Inside the Request's then() Callback
The simplest fix is to wait until the user data is successfully fetched before setting up your Echo channel. Just move your Echo code inside the then() block:
mounted() { this.$http .get('/api/user') .then(response => { this.user = response.data; // Now that user is populated, set up Echo this.$echo .channel(`new-notification.${this.user.id}`) .listen('NewNotification', (data) => { // eslint-disable-next-line no-alert this.notifications.unshift(data); }); }) .catch(error => console.log(error)); },
Fix 2: Use async/await for Cleaner Code
If you prefer more readable asynchronous code, you can turn your mounted hook into an async function and await the Axios request:
async mounted() { try { const response = await this.$http.get('/api/user'); this.user = response.data; // Set up Echo once user data is ready this.$echo .channel(`new-notification.${this.user.id}`) .listen('NewNotification', (data) => { // eslint-disable-next-line no-alert this.notifications.unshift(data); }); } catch (error) { console.log(error); } },
Quick Optimization: Fix the Initial user Value
One small thing: your API returns a user object, not an array. In your data(), you initialized user as an empty array []—this is a bit misleading. Change it to an empty object {} to match the actual data structure:
data() { return { user: {}, // Empty object instead of array notifications: [] // I assume you have this for storing notifications! }; },
This makes your code more consistent and avoids any confusion down the line.
内容的提问来源于stack exchange,提问作者aaaaronjmnz

