Magento official document has written the good guide on this, do check it out! I hope it will be helpful for you.
That's the error cause mentioned by Magento in their guide:
"The error occurs because the setup:di:compile command tries to access the var/di and var/generation directories, which are read-only.
It is not a defect but an expected behavior on cloud environments. You should not run setup:di:compile manually since this command is being executed during the deployment process. The Magento code cannot be changed on the fly (because it is located in the read-only directories), so there is no need to recompile var/di and var/generation: there is no difference with files generated during deployment."
For further read: https://support.magento.com/hc/en-us/articles/115002663433-Error-running-the-setup-di-compile-command-manually