The short answer is that it is due to stress.
In primatology self-harm is called self-injurious behavior (SIB) and is associated with anxiety. The single most common denominator among animals who self-harm is isolation — social isolation. Primates bite themselves, parrots pull out their feathers and dogs and cats lick themselves. Such self-injurious behavior tends to occur in emotionally disturbing situations, particular those over which the individual has little or no control (like being locked up alone).
Stress can cause tail biting in swine or self-mutilation in monkeys. Tail biting in pigs is an abnormal behavior whereby a pig uses its teeth to bite, chew or orally manipulate another pigs's tail. Tail biting typically occurs under the following stressors: indoor facility with a high density of pigs housed in a confined area (like a pen); lack of a substrate material; poor ventilation system, or poor feed quality and accessibility. In another case rhesus macaques monkeys displayed self biting behavior. They repeatedly bite part of their own bodies while intermittently showing signs of intense excitation such as threatening, trembling, head jerking and piloerection. The stressor in this case was the stress from relocation and isolation.
Bonobo apes were observed to pull their hair out leaving patches of hairless skin. I searched for an answer, and ran across the story of a bonobo mother who actually pulled her child’s hair out. She did it for so long that the hair stopped growing back. This was not aggression, but “grooming gone wild”. Grooming is nature’s self-soothing strategy. Animals groom others as well as themselves, and that builds soothing social bonds. When the going gets tough, mammals groom. Many repetitive behaviors are variants on grooming. The behavior may get repeated endlessly if a mammal has a persistent sense of threat.
Intelligent species of parrots often pull out their own feathers when they are very unhappy. Known causes include loneliness and isolation from other parrots to interact with, stress from loud noises or not turning lights off at night, and boredom from not having enough to do in their cages (toys, climbing areas, room to move around).
King snakes will eat their own tail if they are stressed by overheating.
Given that social isolation, stress and anxiety are the triggers and main reason for self-injury, reducing stress and increasing time spent with others would be the most effective. Massage solves both and has demonstrated effectiveness for a wide range of conditions.