setCapability of device on receiving mqtt message

I’m trying to set a device capability value when a message is received through mqtt.
Here is the device.js code:

'use strict';

const { Device } = require('homey');
const DeviceApi = require('./device-api');

class MyDevice extends Device {

  /**
   * onInit is called when the device is initialized.
   */
  async onInit() {
    this.log('Device has been initialized');
    this.mqttconn = await DeviceApi.connectMQTT();
    this.mqttconn.on('connect', function() {
      console.log('connected');
    });
    this.mqttconn.subscribe('tswoonkamer/target_temperature', { qos: 1 });
    this.mqttconn.on('message', function( topic, message, packet) {
      const msg = JSON.parse(message);
      console.log(msg.temp);
      this.setCapabilityValue('measure_temperature', value); // Fails horribly..
    });

  }

I’m getting a this.setCapabilityValue is not a function error when a message is received.
Pretty sure this is me not understanding something fundamental, so any pointer in the right direction would be great.

Correct: in normal functions, this will be bound to the function, not to the outside (in other words, this inside the function is not the same as this outside the function).

The easiest fix is to use arrow functions, which don’t have this binding:

    this.mqttconn.on('message', ( topic, message, packet) => {
      const msg = JSON.parse(message);
      console.log(msg.temp);
      this.setCapabilityValue('measure_temperature', value); // Fails horribly..
    });

Thank you !! Was running in the dark blindfolded.

This totally fixed it.